home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 4.iso / FAQs / netfaqs / perl-faq < prev    next >
Text File  |  1994-08-01  |  118KB  |  3,073 lines

  1.  
  2. Newsgroups: comp.lang.perl,news.answers
  3. From: Tom Christiansen <tchrist@cs.Colorado.EDU>
  4. Subject: Perl Frequently Asked Questions, part 0 of 4
  5. Followup-To: comp.lang.perl
  6. Originator: tchrist@wraeththu.cs.colorado.edu
  7. Sender: news@Colorado.EDU (USENET News System)
  8. Organization: University of Colorado at Boulder
  9. Date: Sat, 2 Oct 1993 06:36:20 GMT
  10. Approved: news-answers-request@MIT.Edu
  11. Expires: Wed, 1 Dec 1993 12:00:00 GMT
  12. Lines: 123
  13. Xref: senator-bedfellow.mit.edu comp.lang.perl:20581 news.answers:13119
  14.  
  15. Archive-name: perl-faq/part0
  16. Version: $Id: perl-intro,v 1.5 93/10/02 00:32:46 tchrist Exp Locker: tchrist $
  17.  
  18. This article contains the table of contents to some of the most
  19. frequently asked questions in comp.lang.perl, a newsgroup devoted to
  20. the Perl programming language.  There are four pieces following 
  21. this, the general information questions in part1 and part2 and 
  22. the largely technical ones in part3 and part4.
  23.  
  24. They're all good questions, but they come up often enough that
  25. substantial net bandwidth can be saved by looking here first before
  26. asking.  Before posting a question, you really should consult the Perl
  27. man page; there's a lot of information packed in there.
  28.  
  29. Some questions in this group aren't really about Perl, but rather
  30. about system-specific issues.  You might also consult the Most
  31. Frequently Asked Questions list in comp.unix.questions for answers
  32. to this type of question.
  33.  
  34. The current version of perl is 4.036 (version 4, patchlevel 35).  There
  35. haven't actually been 36 updates to perl4; rather, the context diffs
  36. posted to the net have been broken up into 36 news-digestable chunks.  
  37. The 2nd alpha version of version 5.0 perl is available: vide infra.
  38.  
  39. This list is maintained by Tom Christiansen, and is archived on
  40. convex.com [130.168.1.1] in the file pub/perl/info/faq, as well
  41. as on rtfm.mit.edu [18.70.0.224] in /pub/usenet/comp.lang.perl .
  42. If you have any suggested additions or corrections to this article,
  43. please send them to Tom at either <tchrist@cs.colorado.edu> or
  44. <tchrist@usenix.org> .  Special thanks to Larry Wall for periodically
  45. reviewing this list for accuracy and especially for writing and
  46. releasing Perl in the first place.
  47.  
  48.  
  49. This sections contains answers to general information questions,
  50. mostly of a non-technical nature.  
  51.     1.1) What is Perl?
  52.     1.2) Is Perl hard to learn?
  53.     1.3) Should I program everything in Perl?
  54.     1.4) Where can I get Perl over the Internet?
  55.     1.5) Where can I get Perl via Email?
  56.     1.6) How can I get Perl via UUCP?
  57.     1.7) Where can I get more information on Perl?
  58.     1.8) Can people who aren't on USENET receive comp.lang.perl as a digest?
  59.     1.9) Are archives of comp.lang.perl available?
  60.     1.10) Is there a WAIS server for Perl?
  61.     1.11) Is there a Perl port to machine FOO?
  62.     1.12) How do I get Perl to compile on Solaris?
  63.     1.13) How do I get Perl to compile on a Next?
  64.     1.14) Where can I get (info|inter|ora|sql|syb)perl?
  65.     1.15) Where can I get an SNMP-aware Perl?
  66.     1.16) There's an a2p and an s2p; why isn't there a p2c (perl-to-C)?
  67.     1.17) Where can I get undump for my machine?
  68.     1.18) Where can I get a perl-mode for emacs?
  69.     1.19) How can I use Perl interactively?
  70.     1.20) Is there a Perl shell? 
  71.     1.21) Is there a Perl profiler?
  72.     1.22) Is there a yacc for Perl?
  73.     1.23) How can I use curses with perl?
  74.     1.24) How can I use X with Perl?
  75.     1.25) What is perl4?  What is perl5?
  76.     1.26) How does Perl compare with languages like REXX or TCL?
  77.     1.27) Is it a Perl program or a Perl script?
  78.     1.28) What's the difference between "Perl" and "perl"?
  79.     1.29) What companies use or ship Perl?
  80.     1.30) Is there commercial, 3rd-party support for Perl?
  81.     1.31) Where can I get a list of the JAPH signature quotes?
  82.     1.32) Where can I get a list of Larry Wall witticisms?
  83.     1.33) Is there a pretty-printer for Perl?
  84.     1.34) Can I dynamically load C user routines?
  85.  
  86. This section contains answers to the following technical questions
  87. regarding Perl:
  88.     2.1) What are all these $@*%<> signs and how do I know when to use them?
  89.     2.2) Why don't backticks work as they do in shells?  
  90.     2.3) How come Perl operators have different precedence than C operators?
  91.     2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  92.     2.5) How can I call my system's unique C functions from Perl?
  93.     2.6) Where do I get the include files to do ioctl() or syscall()?
  94.     2.7) Why doesn't "local($foo) = <FILE>;" work right?
  95.     2.8) How can I detect keyboard input without reading it, 
  96.     2.9) how can I read a single character from the keyboard under UNIX and DOS?
  97.     2.10) How can I make an array of arrays or other recursive data types?
  98.     2.11) How do I make an array of structures containing various data types?
  99.     2.12) How can I quote a variable to use in a regexp?
  100.     2.13) Why do setuid Perl scripts complain about kernel problems?
  101.     2.14) How do I open a pipe both to and from a command?
  102.     2.15) How can I change the first N letters of a string?
  103.     2.16) How can I manipulate fixed-record-length files?
  104.     2.17) How can I make a file handle local to a subroutine?
  105.     2.18) How can I extract just the unique elements of an array?
  106.     2.19) How can I call alarm() or usleep() from Perl?
  107.     2.20) How can I test whether an array contains a certain element?
  108.     2.21) How can I do an atexit() or setjmp()/longjmp() in Perl?
  109.     2.22) Why doesn't Perl interpret my octal data octally?
  110.     2.23) How do I sort an associative array by value instead of by key?
  111.     2.24) How can I capture STDERR from an external command?
  112.     2.25) Why doesn't open return an error when a pipe open fails?
  113.     2.26) How can I compare two date strings?
  114.     2.27) What's the fastest way to code up a given task in perl?
  115.     2.28) How can I know how many entries are in an associative array?
  116.     2.29) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  117.     2.30) Do I always/never have to quote my strings or use semicolons?
  118.     2.31) How can I translate tildes in a filename?
  119.     2.32) How can I convert my shell script to Perl?
  120.     2.33) What is variable suicide and how can I prevent it?
  121.     2.34) Can I use Perl regular expressions to match balanced text?
  122.     2.35) Can I use Perl to run a telnet or ftp session?
  123.     2.36) What does "Malformed command links" mean?
  124.     2.37) How can I set up a footer format to be used with write()?
  125.     2.38) Why does my Perl program keep growing in size?
  126.     2.39) Can I do RPC in Perl?
  127.     2.40) What's the difference between delete and undef with %tables?
  128.     2.41) How do I do a "tail -f" in Perl?
  129.  
  130.  
  131. -------------------------------------------------------------------------------
  132.  
  133.  
  134. 1.1) What is Perl?
  135.  
  136.     A programming language, by Larry Wall <lwall@netlabs.com>.
  137.  
  138.     Here's the beginning of the description from the man page:
  139.  
  140.     Perl is an interpreted language optimized for scanning arbitrary text
  141.     files, extracting information from those text files, and printing reports
  142.     based on that information.  It's also a good language for many system
  143.     management tasks.  The language is intended to be practical (easy to use,
  144.     efficient, complete) rather than beautiful (tiny, elegant, minimal).  It
  145.     combines (in the author's opinion, anyway) some of the best features of C,
  146.     sed, awk, and sh, so people familiar with those languages should have
  147.     little difficulty with it.  (Language historians will also note some
  148.     vestiges of csh, Pascal, and even BASIC-PLUS.)  Expression syntax
  149.     corresponds quite closely to C expression syntax.  Unlike most Unix
  150.     utilities, Perl does not arbitrarily limit the size of your data--if
  151.     you've got the memory, Perl can slurp in your whole file as a single
  152.     string.  Recursion is of unlimited depth.  And the hash tables used by
  153.     associative arrays grow as necessary to prevent degraded performance.
  154.     Perl uses sophisticated pattern matching techniques to scan large amounts
  155.     of data very quickly.  Although optimized for scanning text, Perl can also
  156.     deal with binary data, and can make dbm files look like associative arrays
  157.     (where dbm is available).  Setuid Perl scripts are safer than C programs
  158.     through a dataflow tracing mechanism which prevents many stupid security
  159.     holes.  If you have a problem that would ordinarily use sed or awk or sh,
  160.     but it exceeds their capabilities or must run a little faster, and you
  161.     don't want to write the silly thing in C, then Perl may be for you.  There
  162.     are also translators to turn your sed and awk scripts into Perl scripts.
  163.  
  164.  
  165. 1.2) Is Perl hard to learn?
  166.     
  167.     No, Perl is easy to learn for two reasons.  
  168.    
  169.     The first reason is that most of Perl is derived from existing tools
  170.     and languages, ones that many people who turn to Perl already have
  171.     some familiarity with.  These include the C programming language, the
  172.     UNIX C library, the UNIX shell, sed, and awk.  If you already know
  173.     these somewhat, Perl should be very easy for you.
  174.  
  175.     The second reason that Perl is easy to learn is that you don't have to
  176.     know every thing there is to know about it in order to get good use
  177.     out of it.  In fact, just a very small subset, mostly borrowed from C,
  178.     the shell, and sed, will be enough for most tasks.  As you feel the
  179.     need or desire to use more sophisticated features (such as C
  180.     structures or networking), you can learn these as you go.  The
  181.     learning curve for Perl is not a steep one, especially if you have
  182.     the headstart of having a background in UNIX.  Rather, its learning
  183.     curve is gentle and gradual, but it *is* admittedly rather long.
  184.  
  185.     If you don't know C or UNIX at all, it'll be a steeper learning curve,
  186.     but what you then learn from Perl will carry over into other areas,
  187.     like using the C library, UNIX system call, regular expressions, and
  188.     associative arrays, just to name a few.  To know Perl is to know 
  189.     UNIX, and vice versa.
  190.  
  191.  
  192. 1.3) Should I program everything in Perl?
  193.  
  194.     Of course not.  You should choose the appropriate tool for the task at
  195.     hand.  While it's true that the answer to the question "Can I do (some
  196.     arbitrary task) in Perl?" is almost always "yes", that doesn't mean
  197.     this is necessarily a good thing to do.  For many people, Perl serves
  198.     as a great replacement for shell programming.  For a few people, it
  199.     also serves as a replacement for most of what they'd do in C.  But
  200.     for some things, Perl just isn't the optimal choice, such as tasks
  201.     requiring very complex data structures.
  202.  
  203.  
  204. 1.4) Where can I get Perl over the Internet?
  205.  
  206.     From any comp.sources.misc archive.   Initial sources  were posted to
  207.     Volume 18, Issues 19-54 at patchlevel 3.  The Patches 4-10 were posted
  208.     to Volume 20, Issues 56-62.  You can use the archie server
  209.     (see the alt.sources FAQ in news.answers) for ways to find these.
  210.  
  211.     These machines, at the very least, definitely have it available for
  212.     anonymous FTP:
  213.  
  214.     ftp.uu.net                137.39.1.2
  215.     ftp.netlabs.com         192.94.48.152
  216.     coombs.anu.edu.au        150.203.76.2
  217.     archive.cis.ohio-state.edu      128.146.8.52
  218.     jpl-devvax.jpl.nasa.gov         128.149.1.143
  219.     prep.ai.mit.edu            18.71.0.38
  220.     ftp.cs.ruu.nl            131.211.80.17  (Europe)
  221.  
  222.     Larry's machine is the netlabs one, and the biggest Perl archive
  223.     is on coombs.
  224.  
  225.  
  226. 1.5) Where can I get Perl via Email?
  227.  
  228.     If you are in Europe, you might using the following site.  (I'm still
  229.     looking for a domestic site.) This information thanks to "Henk P.
  230.     Penning" <henkp@cs.ruu.nl>:  One automated fashion is as follows:
  231.  
  232.     Email: Send a message to 'mail-server@cs.ruu.nl' containing:
  233.      begin
  234.      path your_email_address
  235.      send help
  236.      send PERL/INDEX
  237.      end
  238.     The path-line may be omitted if your message contains a normal From:-line.
  239.     You will receive a help-file and an index of the directory that contains
  240.     the Perl stuff.
  241.  
  242.     If all else fails, mail to Larry usually suffices.
  243.  
  244.  
  245. 1.6) How can I get Perl via UUCP?
  246.  
  247.     You can get it from the site osu-cis; here is the appropriate info,
  248.     thanks to J Greely <jgreely@cis.ohio-state.edu> or <osu-cis!jgreely>.
  249.  
  250.     E-mail contact:
  251.         osu-cis!uucp
  252.     Get these two files first:
  253.         osu-cis!~/GNU.how-to-get.
  254.         osu-cis!~/ls-lR.Z
  255.     Current Perl distribution:
  256.         osu-cis!~/perl/4.0/kits@10/perl.kitXX.Z (XX=01-37)
  257.     How to reach osu-cis via uucp(L.sys/Systems file lines):
  258.     #
  259.     # Direct Trailblazer
  260.     #
  261.     osu-cis Any ACU 19200 1-614-292-5112 in:--in:--in: Uanon
  262.     #
  263.     # Direct V.32 (MNP 4)
  264.     # dead, dead, dead...sigh.
  265.     #
  266.     #osu-cis Any ACU 9600 1-614-292-1153 in:--in:--in: Uanon
  267.     #
  268.     # Micom port selector, at 1200, 2400, or 9600 bps.
  269.     # Replace ##'s below with 12, 24, or 96 (both speed and phone number).
  270.     #
  271.     osu-cis Any ACU ##00 1-614-292-31## "" \r\c Name? osu-cis nected \c GO \d\r\d\r\d\r in:--in:--in:
  272.      Uanon
  273.  
  274.     Modify as appropriate for your site, of course, to deal with your
  275.     local telephone system.  There are no limitations concerning the hours
  276.     of the day you may call.
  277.  
  278.     Another possibility is to use UUNET, although they charge you
  279.     for it.  You have been duly warned.  Here's the advert:
  280.  
  281.            Anonymous Access to UUNET's Source Archives
  282.  
  283.                  1-900-GOT-SRCS
  284.  
  285.      UUNET now provides access to its extensive collection of UNIX
  286.     related sources to non- subscribers.  By  calling  1-900-468-7727
  287.     and  using the login "uucp" with no password, anyone may uucp any
  288.     of UUNET's on line source collection.  Callers will be charged 40
  289.     cents  per  minute.   The charges will appear on their next tele-
  290.     phone bill.
  291.  
  292.      The  file  uunet!/info/help  contains  instructions.   The  file
  293.     uunet!/index//ls-lR.Z contains a complete list of the files available
  294.     and is updated daily.  Files ending in Z need to be uncompressed
  295.     before being used.   The file uunet!~/compress.tar is a tar
  296.     archive containing the C sources for the uncompress program.
  297.  
  298.      This service provides a  cost  effective  way  of  obtaining
  299.     current  releases  of sources without having to maintain accounts
  300.     with UUNET or some other service.  All modems  connected  to  the
  301.     900  number  are  Telebit T2500 modems.  These modems support all
  302.     standard modem speeds including PEP, V.32 (9600), V.22bis (2400),
  303.     Bell  212a  (1200), and Bell 103 (300).  Using PEP or V.32, a 1.5
  304.     megabyte file such as the GNU C compiler would cost $10  in  con-
  305.     nect  charges.   The  entire  55  megabyte X Window system V11 R4
  306.     would cost only $370 in connect time.  These costs are less  than
  307.     the  official  tape  distribution fees and they are available now
  308.     via modem.
  309.  
  310.               UUNET Communications Services
  311.            3110 Fairview Park Drive, Suite 570
  312.              Falls Church, VA 22042
  313.              +1 703 876 5050 (voice)
  314.               +1 703 876 5059 (fax)
  315.                 info@uunet.uu.net
  316.  
  317.  
  318.  
  319. 1.7) Where can I get more information on Perl?
  320.  
  321.     We'll cover five areas here: USENET (where you're probably reading
  322.     this), publications, the reference guide, examples on the Internet,
  323.     and Perl instructional courses.
  324.  
  325.     A.  USENET
  326.  
  327.     You should definitely read the USENET comp.lang.perl newsgroup or
  328.     mailing list for all sorts of discussions regarding the language,
  329.     bugs, features, history, humor, and trivia.  In this respect, it
  330.     functions both as a comp.lang.* style newsgroup and also as a user
  331.     group for the language; in fact, there's a mailing list called
  332.     ``perl-users'' that is bidirectionally gatewayed to the newsgroup; see
  333.     question #38 for details.  Larry Wall is a very frequent poster here,
  334.     as well as many (if not most) of the other seasoned Perl programmers.
  335.     It's the best place for the very latest information on Perl.
  336.  
  337.     B.  PUBLICATIONS
  338.  
  339.     If you've been dismayed by the ~80-page troffed Perl man page (or is
  340.     that man treatise?) you should look to ``the Camel Book'', written by
  341.     Larry and Randal Schwartz <merlyn@ora.com>, published as a Nutshell
  342.     Handbook by O'Reilly & Associates and entitled _Programming Perl_.
  343.     Besides serving as a reference guide for Perl, it also contains
  344.     tutorial material and is a great source of examples and cookbook
  345.     procedures, as well as wit and wisdom, tricks and traps, pranks and
  346.     pitfalls.  The code examples contained therein are available via
  347.     anonymous FTP from ftp.uu.net in
  348.     /published/oreilly/nutshell/perl/perl.tar.Z for your retrieval.
  349.     Corrections and additions to the book can be found in the Perl man
  350.     page right before the BUGS section under the heading ERRATA AND
  351.     ADDENDA.  
  352.  
  353.     If you can't find the book in your local technical bookstore, the book
  354.     may be ordered directly from O'Reilly by calling 1-800-998-9938 if in
  355.     North America and 1-707-829-0515.  The book's ISBN is 0-937175-64-1.
  356.    
  357.     Autographed copies are *NO LONGER* available from TECHbooks --
  358.     you'll have to nab the authors in person if you want one.  Larry
  359.     routinely carries around a camel stamp for just such an occasion.
  360.  
  361.     Reasonably substantiated rumor has it that there will be another Perl
  362.     book out pretty soon, this one aimed more at beginners.  Look for it
  363.     from ORA towards the beginning of 93.
  364.    
  365.     Another ORA book by Randal Schwartz is scheduled for imminent
  366.     release.  It is entitled _Learning Perl_ (``The LLama Book'') and
  367.     covers the basics of Perl in a tutorial fashion.
  368.  
  369.     Larry Wall has published a 3-part article on perl in Unix World
  370.     (August through October of 1991), and Rob Kolstad also had a 3-parter
  371.     in Unix Review (May through July of 1990).  Tom Christiansen also has
  372.     a brief overview article in the trade newsletter Unix Technology
  373.     Advisor from November of 1989.  You might also investigate "The Wisdom
  374.     of Perl" by Gordon Galligher from SunExpert magazine;  April 1991
  375.     Volume 2 Number 4.  The Dec 92 Computer Language magazine also
  376.     contains a cover article on Perl, "Perl: the Programmers Toolbox".
  377.  
  378.     Many other articles on Perl have been recently published.  If you 
  379.     have references, especially on-line copies, please mail them to 
  380.     the FAQ maintainer for inclusion is this notice.
  381.  
  382.     The USENIX LISA (Large Installations Systems Administration) Conference
  383.     have for several years now included many papers of tools written in
  384.     Perl.  Old proceedings of these conferences are available; look in
  385.     your current issue of ";login:" or send mail to office@usenix.org 
  386.     for further information.
  387.  
  388.     C.  INTERNET
  389.  
  390.     For other examples of Perl scripts, look in the Perl source directory in
  391.     the eg subdirectory.  
  392.  
  393.     The site with the biggest repository of Perl scripts right now
  394.     seems to be coombs.anu.edu.au [150.203.76.2].  That directory
  395.     has an INDEX with over 300 lines in it, each describing what
  396.     the script does.  This is maintained by mark@coombs.anu.edu.au .
  397.  
  398.     Note:  European users please use the mirror site on
  399.     src.doc.ic.ac.uk[149.169.2.1 in
  400.         /pub/computing/programming/languages/perl/coombs-scripts
  401.     The link speed would be a lot better for all.  Contact
  402.     L.McLoughlin@doc.ic.ac.uk for more information. It is updated daily.
  403.  
  404.     Another source for examples, currently only for anonymous FTP, is on
  405.     convex.com [130.168.1.1].  This contains, amongst other things,
  406.     a copy of the newsgroup up through Aug 91, a text retrieval database
  407.     for the newsgroup, a rather old and short troff version of Tom Christiansen's
  408.     perl tutorial (this was the version presented at Washington DC USENIX),
  409.     and quite a few of Tom's scripts.  You can look at the INDEX file
  410.     in /pub/perl/INDEX for a list of what's in that directory.   
  411.  
  412.     The Convex and Ohio State archives are mirrored on uunet
  413.     in /languages/perl/scripts-{convex,osu}.
  414.  
  415.     There's also a #Perl channel on IRC (Internet Relay Chat) where
  416.     Tom and Randal have been known to hang out.  That's real-time,
  417.     free Perl support.  What more can you ask? :-)
  418.  
  419.     D.  REFERENCE GUIDE
  420.  
  421.     A nice reference guide by Johan Vromans <jv@mh.nl> is also available;
  422.     It is distributed in LaTeX (source) and PostScript (ready to
  423.     print) forms. Obsolete versions may still be available in TeX and troff
  424.     forms, although these don't print as nicely. The official kit
  425.     includes both LaTeX and PostScript forms, and can be FTP'd from
  426.     ftp.cs.ruu.nl [131.211.80.17], file /pub/DOC/perlref-4.035.tar.Z.
  427.     The reference guide comes with the O'Reilly book in a nice, glossy
  428.     card format.
  429.  
  430.     E.  PERL COURSES
  431.  
  432.     Various technical conferences, including USENIX, LISA, SUG, WCSAS, AUUG,
  433.     FedUnix, and Europen have been sponsoring tutorials of varying lengths
  434.     on Perl at their system administration and general conferences.  You
  435.     might consider attending one of these.  These public classes are
  436.     typically taught by Tom Christiansen <tchrist@usenix.com>.  Both Tom
  437.     and Randal Schwartz <merlyn@ora.com> also teach Perl at customer
  438.     sites.  Classes can run from one day up to a week ranging over a wide
  439.     range of subject matter (most are two or three days), and can include
  440.     lab time if you want; having lab time with exercises is generally of
  441.     great benefit.  Send us mail if your organization is interested in
  442.     having a Perl class taught at your site, or if you'd like to know when
  443.     the next public appearances are.
  444.  
  445.  
  446. 1.8) Can people who aren't on USENET receive comp.lang.perl as a digest?
  447.  
  448.     "Perl-Users" is the mailing list version of the comp.lang.perl
  449.     newsgroup.  If you're not lucky enough to be on USENET you can post to
  450.     comp.lang.perl by sending to one of the following addresses.  Which one
  451.     will work best for you depends on which nets your site is hooked into.
  452.     Ask your local network guru if you're not certain.
  453.  
  454.     Internet: PERL-USERS@VIRGINIA.EDU
  455.               Perl-Users@UVAARPA.VIRGINIA.EDU
  456.  
  457.     BitNet: Perl@Virginia
  458.  
  459.     uucp: ...!uunet!virginia!perl-users
  460.  
  461.     The Perl-Users list is bidirectionally gatewayed with the USENET
  462.     newsgroup comp.lang.perl.  This means that VIRGINIA functions as a
  463.     reflector.  All traffic coming in from the non-USENET side is
  464.     immediately posted to the newsgroup.  Postings from the USENET side are
  465.     periodically digested and mailed out to the Perl-Users mailing list.  A
  466.     digest is created and distributed at least once per day, more often if
  467.     traffic warrants.
  468.  
  469.     All requests to be added to or deleted from this list, problems,
  470.     questions, etc., should be sent to:
  471.  
  472.     Internet: Perl-Users-Request@Virginia.EDU
  473.               Perl-Users-Request@uvaarpa.Virginia.EDU
  474.  
  475.     BitNet: Perl-Req@Virginia
  476.  
  477.     uucp: ...!uunet!virginia!perl-users-request
  478.  
  479.     Coordinator: Marc Rouleau <mer6g@VIRGINIA.EDU>
  480.  
  481. 1.9) Are archives of comp.lang.perl available?
  482.  
  483.     Yes, although they're poorly organized.  You can get them from the
  484.     host ftp.ugcs.caltech.edu (131.215.128.204) to the file
  485.     /pub/comp.lang.perl.tar.Z; this file was last modified on February 15,
  486.     1992, and is 8.9 megabytes long.  Obviously, it's considerably out of
  487.     date.
  488.  
  489.     These are currently stored in news- or MH-style format; there are
  490.     subdirectories named things like "arrays", "programs", "taint", and
  491.     "emacs".  Unfortunately, only the first ~1600 or so messages have been
  492.     so categorized, and we're now up to almost 15000.  Furthermore, even
  493.     this categorization was haphazardly done and contains errors.  
  494.  
  495.     Both Larry and I have maintained archives of the nearly 19,000
  496.     messages the newsgroup has seen since its inception.  I'm currently
  497.     looking for a home for them.  It'll take about 100 megabytes, although
  498.     I'm on a 16k/2k filesystem, and that might be reduced somewhat by one
  499.     with smaller frags.  Or perhaps I'll just get myself a new disk.
  500.  
  501.     They're just stored as regular files the way news does, so it's
  502.     somewhat unmanageable.
  503.  
  504.     A more sophisticated query and retrieval mechanism is desirable.
  505.     Preferably one that allows you to retrieve article using a fast-access
  506.     indices, keyed on at least author, date, subject, thread (as in "trn")
  507.     and probably keywords.  Right now, the MH pick command works for this,
  508.     but it is very slow to select on 18000 articles.
  509.  
  510.     If you're serious about this, your best bet is probably to retrieve
  511.     the compressed tarchive and play with what you get.  Any suggestions
  512.     how to better sort this all out are extremely welcome.
  513.  
  514.     If you have a special request for a query on the old newsgroup
  515.     postings, and make nice noises in my direction, I can run the query
  516.     and send them to you.  Algebraic queries are like "find me anything
  517.     about this and that and the other thing but not this or whozits".  I
  518.     hope to put this in the form of a mailserver.  Donated software would
  519.     be fine. :-)
  520.  
  521.     The fast text-retrieval query system for this I'm currently using is
  522.     Liam Quin's excellent lqtext system, available from ftp.cs.toronto.edu
  523.     in /pub/lq-text* .
  524.  
  525.  
  526. 1.10) Is there a WAIS server for Perl?
  527.  
  528.     Rumor has it that there are WAIS servers out there for comp.lang.perl
  529.     these days, but I haven't used them.  Kevin Gardner <gardner@zinc.csb.yale.edu> 
  530.     offers the following: For WAIS server info, check on the gopher hole
  531.     at mudhoney.micro.umn.edu, port 70.  They've got a rather extensive
  532.     list of WAIS servers at this gopher->WAIS gateway, including a c.l.p.
  533.     archive server.  I don't know how up to date the server actually is,
  534.     as the articles I pulled up from there were all dated from '91.
  535.  
  536.     Bill Middleton <wjm@feenix.metronet.com> offers this:
  537.  
  538.     "I have setup a perl script retrieval service and WaisSearch here at
  539.     feenix.  To check it out, just point your gopher at us, and select the
  540.     appropriate menu option.  The WaisSearch is of the iubio type, which
  541.     means you can do boolean searching.  Thus you might try something
  542.     like:
  543.  
  544.     caller
  545.     ioctl and fcntl
  546.     grep and socket not curses
  547.  
  548.     and other things to see examples of how other folks have done this
  549.     or that.  This service is still under construction, but I'd like to
  550.     get feedback, if you have some time.
  551.  
  552.     There's also a WaisSearch into all the RFC's and some other fairly
  553.     nifty stuff."
  554.  
  555.  
  556. 1.11) Is there a Perl port to machine FOO?
  557.  
  558.     Probably.  Perl already runs on virtually all UNIX machines as well as 
  559.     quite a few non-UNIX ones.  Chances are that if you're running a UNIX
  560.     box, you simply need to run Configure and everything will be taken
  561.     care of for you.   For most UNIX machines, no porting is required.
  562.  
  563.     Perl comes with an elaborate auto-configuration script that allows Perl
  564.     to be painlessly ported to a wide variety of platforms, including many
  565.     non-UNIX ones.  Amiga and MS-DOS binaries are available on
  566.     jpl-devvax.jpl.nasa.gov [128.149.1.143] for anonymous FTP.  Try to bring
  567.     Perl up on your machine, and if you have problems, examine the README
  568.     file carefully, and if all else fails, post to comp.lang.perl with 
  569.     a cross-posting to comp.sys.whatever; probably someone out there has
  570.     run into your problem and will be able to help you.  
  571.  
  572.     In the perl archive on coombs.anu.edu.au, you can consult the file
  573.     /pub/perl/misc/perl.code.sources for information not contained below.
  574.     It may also be more up-to-date as well.
  575.  
  576.     In particular, since they're so often asked about, here's some information 
  577.     for the MacIntosh from Matthias Ulrich Neeracher <neeri@iis.ethz.ch>:
  578.  
  579.         The most recent version of Perl for the Apple Macintosh using the
  580.         MPW C compiler is available in:
  581.  
  582.             nic.switch.ch [130.59.1.40]    software/mac/src/mpw_c
  583.             ftp.eunet.ch  [146.228.10.15]  software/mac/perl
  584.  
  585.         The current version is 4.0.7 (despite the "7", it corresponds to
  586.         patchlevel 36 in the Unix version) and is available in the above
  587.         directories as
  588.  
  589.            Mac_Perl_407_src.sit.bin       Sources
  590.            Mac_Perl_407_tool.sit.bin      MPW Tool
  591.            Mac_Perl_407_appl.sit.bin      Standalone Application (See below)
  592.  
  593.         There is a mailing list for discussing Macintosh Perl which can be
  594.         reached at mpw-perl-request@iis.ee.ethz.ch
  595.  
  596.     Here's more, from Timothy Murphy <tim@maths.tcd.ie >
  597.  
  598.     I ported perl to the Mac, using Think C, a while ago.  I've
  599.     used it quite a lot since without problems.
  600.  
  601.     It is available from ftp.maths.tcd.ie in pub/Mac/perl.hqx .
  602.     The source (as diffs from the standard source) is in the
  603.     subdirectory pub/Mac/perl-4.035 .
  604.  
  605.     A Mac version of patch is also available in pub/Mac/patch.hqx
  606.     with source in pub/Mac/patch-2.0 .  Various other Mac ports of
  607.     GNU programs can be found in the same place.
  608.  
  609.     They all use a small "ThinkCPosix" library containing various
  610.     Unix-like functions, which again can be found in the same
  611.     place.
  612.  
  613.     And here's some VMS information from Rao V. Akella 
  614.     <rao@moose.cccs.umn.edu>:  (this appears to be an old port)
  615.  
  616.     You can pick up Perl for VMS (version 3.0.1.1 patchlevel 4) via
  617.     anonymous ftp from ftp.pitt.edu [130.49.253.1] in the
  618.     software/vms/perl subdirectory (there are two files there:
  619.     perl-pl18.bck and perl-pl4.bck).
  620.  
  621.     There is also a v3.018 on info.rz.uni-ulm.de [134.60.1.125] or
  622.     vms.huji.ac.il [128.139.4.3] in /pub/VMS/misc (information courtesy 
  623.     of Anders Rolff <rolff@scotty.eurokom.ie>).
  624.  
  625.     And here is a recent version for MS-DOS from Budi Rahardjo
  626.     <rahard@ee.UManitoba.CA>, who says:
  627.  
  628.     I am collecting MS-DOS Perl(s) in ftp.ee.umanitoba.ca directory
  629.     /pub/msdos/perl.  Currently I received three versions of Perl v4.019
  630.     and one of 4.010.  (Tommy Thorn <tthorn@daimi.aau.dk> and Len Reed
  631.     <holos0!lbr@gatech.edu>)  
  632.  
  633.     There is now a 4.035 for 386 [DOS], Hitoshi Doi <doi@jrd.december.com>
  634.     port, is available ftp.ee.umanitoba.ca as /pub/msdos/perl/perl386.zoo .
  635.  
  636.     Please contact the porters directly in case of questions about
  637.     these ports.
  638.  
  639.  
  640.     A new version of "bigperl4" has been uploaded to Simtel20 and mirror
  641.     sites:
  642.  
  643.         pd1:<msdos.perl>
  644.         BPERL2X.ZIP        32-bit Perl 4.0pl36 w/VM & Win 3.1 supt. (exe)
  645.         BPERL2S1.ZIP       32-bit Perl 4.0pl36 w/VM & Win supt. (src 1/2)
  646.         BPERL2S2.ZIP       32-bit Perl 4.0pl36 w/VM & Win supt. (src 2/2)
  647.  
  648.      For those of you who don't know what "bigperl4" is, here's the
  649.     short description:
  650.  
  651.     BIGPERL4 is Perl 4.0pl36 that has been compiled using the Watcom C/386
  652.     compiler (a 32-bit, flat-memory model C compiler), which gives this
  653.     version the following features:
  654.  
  655.       * Up to 32MB of memory can be used.
  656.       * Supports virtual memory.
  657.       * Works under Windows 3.1 (however, a second copy of perl cannot
  658.         be spawned under Windows).
  659.       * The perl debugger can be used.
  660.       * Contains GDBM support.
  661.  
  662.     A 386/486 with at least 4MB RAM is required, and a third-party memory
  663.     manager such as QEMM is strongly recommended.
  664.  
  665.     BIGPERL4 also passes those perl tests that do not depend on Unix-isms.
  666.     Full sources are included (including GDBM 1.5).  Freeware and copylefted
  667.     (in the case of GDBM 1.5).
  668.  
  669.     For a version that works on NT, FTP to rhino.microsoft.com
  670.     (131.107.1.121) the port of Perl there purportedly works well and
  671.     includes support for sockets from perl. The source builds out of the
  672.     box and contains some NT specific tests.
  673.  
  674.  
  675. 1.12) How do I get Perl to compile on Solaris?
  676.  
  677.     John Lees <lees@pixel.cps.msu.edu> reports:
  678.  
  679.     I have built perl on Solaris 2.1, 2.2 beta, and 2.2 FCS. Take /usr/ucb
  680.     out of your path and do not use any BSD/UCB libraries.  Only -lsocket,
  681.     -lnsl, and -lm are needed. You can use the hint for Solaris 2.0, but
  682.     the one for 2.1 is wrong. Do not use vfork. Do not use
  683.     -I/usr/ucbinclude.  The result works fine for me, but of couse does
  684.     not support a couple of BSDism's.
  685.  
  686.     Casper H.S. Dik <casper@fwi.uva.nl> reports
  687.  
  688.     You must remove all the references to /usr/ucblib AND
  689.     /usr/ucbinclude.  And ignore the Solaris_2.1 hints. They are wrong.
  690.     The undefining of vfork() probably ahs to do with the confusion it
  691.     gives to the compilers.  If you use cc, you mustn't compile
  692.     util.c/tutil.c  with -O.  I only used the following libs: -lsocket
  693.     -lnsl -lm (there is a problem with -lmalloc)
  694.  
  695.     Michael D'Errico <mike@software.com> reports:
  696.  
  697.     If you are using Solaris 2.x, the signal handling is broken.  If you set
  698.     up a signal handler such as 'ripper' it will be forgotten after the first
  699.     time the signal is caught.  To fix this, you need to recompile Perl.  Just
  700.     add '#define signal(x,y) sigset((x),(y))' after the '#include <signal.h>'
  701.     directive in each file that it occurs, then make it again.
  702.  
  703.  
  704. 1.13) How do I get Perl to compile on a Next?
  705.  
  706.     Bill Eldridge <bill@cognet.ucla.edu> reports:
  707.  
  708.     To get perl to compile on Nexts, you need to combine the
  709.     ansi and bsd headers:
  710.  
  711.         cd /usr/include
  712.         mkdir ansibsd
  713.         cd ansibsd
  714.         ln -s ../ansi
  715.         ln -s ../bsd
  716.  
  717.     Then follow the configuration instructions for Nexts, *replacing*
  718.     all mention of -I/usr/include/ansi or -I/usr/include/bsd with
  719.     -I/usr/include/ansibsd.  
  720.  
  721.     (There might be more elegant solutions, but this is how I
  722.     did it, and it's quick and so far painless).
  723.  
  724.  
  725.  
  726. 1.14) Where can I get (info|inter|ora|sql|syb)perl?
  727.  
  728.     Numerous database-oriented extensions to Perl have been written.
  729.     These amount to using the usub mechanism (see the usub/ subdirectory
  730.     in the distribution tree) to link in a database library, allowing
  731.     embedded calls to Informix, Interbase, Oracle, Ingres, and Sybase.
  732.     There is currently a project underway, organized by Buzz Moschetti
  733.     <buzz@toxicavenger.bear.com>, to create a higher level interface
  734.     (DBperl) that will allow you to write your queries in a
  735.     database-independent fashion.  If you're interested, send 
  736.     mail to <perldb-interest-request@vix.com> and ask to be placed on the
  737.     perldb-interest@vix.com mailing list.
  738.    
  739.     Meanwhile, here are the authors of the various extensions:
  740.  
  741.     What            Target DB       Who
  742.     --------        -----------     ----------------------------------------
  743.     Infoperl        Informix        Kurt Andersen (kurt@hpsdid.sdd.hp.com)
  744.     Interperl       Interbase       Buzz Moschetti (buzz@bear.com)
  745.     Oraperl         Oracle          Kevin Stock (kstock@encore.com)
  746.     Sqlperl         Ingres          Ted Lemon (mellon@ncd.com)
  747.     Sybperl         Sybase          Michael Peppler (mpeppler@itf.ch)
  748.  
  749.     Here's a bit of advertising from Buzz:
  750.  
  751.     Perl is an interpreted language with powerful string, scalar, and array
  752.     processing features developed by Larry Wall that "nicely bridges the
  753.     functionality gap between sh(1) and C."  Since relational DB operations
  754.     are typically textually oriented, perl is particularly well-suited to
  755.     manage the data flows.  The C source code, which is available free of
  756.     charge and runs on many platforms, contains a user-defined function entry
  757.     point that permits a developer to extend the basic function set of the
  758.     language.  The DBperl Group seeks to exploit this capability by creating a
  759.     standardized set of perl function extensions (e.g. db_fetch(), db_attach())
  760.     based the SQL model for manipulating a relational DB, thus providing a
  761.     portable perl interface to a variety of popular RDMS engines including
  762.     Sybase, Oracle, Ingres, Informix, and Interbase.  In theory, any DB engine
  763.     that implements a dynamic SQL interpreter in its HLI can be bolted onto
  764.     the perl front end with predicatable results, although at this time
  765.     backends exist only for the aforementioned five DB engines.
  766.  
  767.     A copy of the latest sybperl (patch level 6) can be found in the DBperl
  768.     archives on ftp.demon.co.uk:/pub/perl/db/sybperl
  769.  
  770.     This archive also contains ports for Ingres, Oracle, Sybase, Informix,
  771.     Unify, Postgres, and Interbase, as well as rdb and shql; it's the home
  772.     of the evolving DBperl API Specification.
  773.  
  774.  
  775. 1.15) Where can I get an SNMP-aware Perl?
  776.  
  777.     snmperl was written by Guy Streeter (streeter@ingr.com), and was
  778.     posted in late February 1993 to comp.protocols.snmp.  The author has
  779.     not made it available for anonymous ftp, archie only reported one site:
  780.  
  781.     Host liasun3.epfl.ch
  782.  
  783.     Location: /pub/net/snmp
  784.            FILE -rw-rw-r--       3407  Aug 11 1992  snmperl.README
  785.            FILE -rw-r--r--      17678  Aug 11 1992  snmperl.tar.Z
  786.  
  787.     Here is the gist of the README:
  788.  
  789.     README  $Revision: 1.1 $
  790.  
  791.     This directory contains the source code to add callable C subroutines
  792.     to perl.  The subroutines implement the SNMP functions "get",
  793.     "getnext", and "set".  They use the freely-distributable SNMP package
  794.     (version 1.1b) from CMU.
  795.  
  796.     USE:
  797.       There are four subroutines defined in the callable interface:
  798.     snmp_get, snmp_next, snmp_set, and snmp_error.
  799.  
  800.       snmp_get and snmp_next implement the GET and GETNEXT operations,
  801.     respectively.  The first two calling arguments are the hostname and
  802.     Community string.  The IP address of the host, as a dotted-quad ASCII
  803.     string, may be used as the hostname.  The rest of the calling
  804.     arguments are a list of variables.  See the CMU package documentation
  805.     for how variables may be specified.
  806.       snmp_set also takes hostname and Community string as arguments.  The
  807.     remaining arguments are a list of triples consisting of variable name,
  808.     variable type, and value.  The variable type is a string, such as
  809.     "INTEGER" or "IpAddress".
  810.       snmp_get, snmp_next, and snmp_set return a list containing
  811.     alternating variables and values.  snmp_get and snmp_next will simply
  812.     omit non-existent variables on return.  snmp_set will fail completely
  813.     if one of the specified variables does not exist (or is read-only).
  814.       snmp_error will return a text string containing some error
  815.     information about the most recent snmp_get|next|set call, if it had an
  816.     error.
  817.  
  818.     OTHER NOTES:
  819.       I didn't find all the places where the CMU library writes to stderr
  820.     or calls exit() directly.
  821.       The changes I made to mib.c involve the formatting of variable values
  822.     for return to the caller.  I took out the descriptive prefix so the
  823.     string contains only the value.
  824.       Enumerated types are returned as a string containing the symbolic
  825.     representation followed in parentheses by the numeric.
  826.  
  827.     DISTRIBUTION and OWNERSHIP
  828.       perl and the CMU SNMP package have their own statements.  Read them.
  829.     The work I've done is free and clear.  Just don't say you wrote it if
  830.     you didn't, and don't say I wrote it if you change it.
  831.  
  832.     Guy Streeter
  833.     streeter@ingr.com
  834.     April 1, 1992 (not a joke!)
  835.  
  836.  
  837. 1.16) There's an a2p and an s2p; why isn't there a p2c (perl-to-C)?
  838.  
  839.     Because the Pascal people would be upset that we stole their name. :-)
  840.  
  841.     The dynamic nature of Perl's do and eval operators (and remember that
  842.     constructs like s/$mac_donald/$mac_gregor/eieio count as an eval) would
  843.     make this very difficult.  To fully support them, you would have to put
  844.     the whole Perl interpreter into each compiled version for those scripts
  845.     using them.  This is what undump does right now, if your machine has it.
  846.     If what you're doing will be faster in C than in Perl, maybe it should
  847.     have been written in C in the first place.  For things that ought to be
  848.     written in Perl, the interpreter will be just about as fast, because the
  849.     pattern matching routines won't work any faster linked into a C program.
  850.     Even in the case of simple Perl programs that don't do any fancy evals, the
  851.     major gain would be in compiling the control flow tests, with the rest
  852.     still being a maze of twisty, turny subroutine calls.  Since these are not
  853.     usually the major bottleneck in the program, there's not as much to be
  854.     gained via compilation as one might think.
  855.  
  856.  
  857. 1.17) Where can I get undump for my machine?
  858.  
  859.     The undump program comes from the TeX distribution.  If you have TeX, then
  860.     you may have a working undump.  If you don't, and you can't get one,
  861.     *AND* you have a GNU emacs working on your machine that can clone itself,
  862.     then you might try taking its unexec() function and compiling Perl with
  863.     -DUNEXEC, which will make Perl call unexec() instead of abort().  You'll
  864.     have to add unexec.o to the objects line in the Makefile.  If you succeed,
  865.     post to comp.lang.perl about your experience so others can benefit from it.
  866.  
  867.     If you have a version of undump that works with Perl, please submit
  868.     its anon-FTP whereabouts to the FAQ maintainer.
  869.  
  870.  
  871. 1.18) Where can I get a perl-mode for emacs?
  872.  
  873.     In the perl4.0 source directory, you'll find a directory called
  874.     "emacs", which contains several files that should help you.
  875.  
  876.  
  877. 1.19) How can I use Perl interactively?
  878.     
  879.     The easiest way to do this is to run Perl under its debugger.
  880.     If you have no program to debug, you can invoke the debugger
  881.     on an `empty' program like this:
  882.  
  883.         perl -de 0
  884.  
  885.     (The more positive amongst us prefer "perl -de 1". :-)
  886.  
  887.     Now you can type in any legal Perl code, and it will be immediately
  888.     evaluated.  You can also examine the symbol table, get stack
  889.     backtraces, check variable Values, and if you want to, set 
  890.     breakpoints and do the other things you can do in a symbolic debugger.
  891.  
  892.  
  893. 1.20) Is there a Perl shell? 
  894.     
  895.    Not really.  Perl is a programming language, not a command
  896.    interpreter.  There is a very simple one called "perlsh"
  897.    included in the Perl source distribution.  It just does this:
  898.  
  899.     $/ = '';        # set paragraph mode
  900.     $SHlinesep = "\n";
  901.     while ($SHcmd = <>) {
  902.         $/ = $SHlinesep;
  903.         eval $SHcmd; print $@ || "\n";
  904.         $SHlinesep = $/; $/ = '';
  905.     }
  906.  
  907.    Not very interesting, eh?  
  908.  
  909.    Daniel Smith <dansmith@autodesk.com> is working on an interactive Perl
  910.    shell called SoftList.  It's currently at version 3.0beta.  SoftList
  911.    3.0 has tcsh-like command line editing, can let you define a file of
  912.    aliases so that you can run chunks of perl or UNIX commands, and so
  913.    on.  You can send mail to him for further information and availability.
  914.  
  915.  
  916. 1.21) Is there a Perl profiler?
  917.  
  918.     While there isn't one included with the perl source distribution (yet)
  919.     various folks have written packages that allow you to do at least some
  920.     sort of profiling.  The strategy usually includes modifying the perl
  921.     debugger to handle profiling.  Authors of these packages include
  922.  
  923.     Wayne Thompson         <me@anywhere.EBay.Sun.COM>
  924.     Ray Lischner         <lisch@sysserver1.mentor.com>
  925.     Kresten Krab Thorup     <krab@iesd.auc.dk>  
  926.  
  927.     The original articles by these folks containing their
  928.     profilers are available on convex.com in 
  929.     /pub/perl/information/profiling.shar via anon ftp.
  930.  
  931.  
  932. 1.22) Is there a yacc for Perl?
  933.  
  934.     Yes!! It's a version of Berkeley yacc that outputs Perl code instead
  935.     of C code!  You can get this from ftp.sterling.com [192.124.9.1] in
  936.     /local/perl-byacc1.8.1.tar.Z, or send the author mail for details.
  937.  
  938.  
  939. 1.23) How can I use curses with perl?
  940.  
  941.     One way is to build a curseperl binary by linking in your C curses
  942.     library as described in the usub subdirectory of the perl sources.
  943.     This requires a modicum of work, but it will be reasonably fast
  944.     since it's all in C (assuming you consider curses reasonably fast. :-)  
  945.     Programs written using this method require the modified curseperl,
  946.     not vanilla perl, to run.  While this is something of a disadvantage,
  947.     experience indicates that it's better to use curseperl than to 
  948.     try to roll your own using termcap directly.
  949.  
  950.     For a good example of using curseperl, you might want to pick up a
  951.     copy of  Steven L Kunz's <skunz@iastate.edu> "perl menus" package
  952.     ("menu.pl") via anonymous FTP from "ftp.iastate.edu".  It's in the
  953.     /pub/perl as
  954.  
  955.     menu.pl.v1.4.shar
  956.     menu.pl.v2.0.shr1
  957.     menu.pl.v2.0.shr2
  958.     menu.pl.v2.0.tar.Z
  959.  
  960.     menus.pl is a complete menu front-end for curseperl and demonstates
  961.     a lot of things (plus it is useful to boot if you want full-screen
  962.     menu selection ability).
  963.  
  964.     Another possibility is to use Henk Penning's cterm package, a curses
  965.     emulation library written in perl.  cterm is actually a separate
  966.     program with which you communicate via a pipe.  It is available from
  967.     ftp.cs.ruu.nl [131.211.80.17] via anonymous ftp. in the directory
  968.     pub/PERL.  You may also acquire the package via email in compressed,
  969.     uuencoded form by sending a message to mail-server@cs.ruu.nl
  970.     containing these lines:
  971.  
  972.     begin
  973.     send PERL/cterm.shar.Z
  974.     end
  975.  
  976.     See the question on retrieving perl via mail for more information on
  977.     how to get retrieve other items of interest from the mail server
  978.     there.
  979.  
  980.  
  981. 1.24) How can I use X with Perl?
  982.  
  983.     Right now, you have several choices.  You can wait for perl5, use
  984.     the WAFE or STDWIN packages, or try to make your own usub bindings. 
  985.  
  986.     Perl5 is anticipated to be released with bindings for X, called 
  987.     guiperl.  An exciting prototype for this, written by Jon Biggar
  988.     <jon@netlabs.com>, Larry's *other* brother-in-law and officemate, 
  989.     is already up and running inside of Netlabs.  This program addresses
  990.     the same dynamic gui-building problem space as does tcl/tk.
  991.     
  992.     If you can't wait or don't think that guiperl will do what you want,
  993.     a stab at Motif bindings was begun by Theodore C. Law
  994.     <TEDLAW@TOROLAB6.VNET.IBM.COM> area.  His article about this is 
  995.     on convex.com in /pub/perl/info/motif for anon ftp.
  996.  
  997.     STDWIN is a library written by Guido van Rossum <guido@cwi.nl>
  998.     (author of the Python programming language) that is portable 
  999.     between Mac, Dos and X11.  One could write a Perl agent to
  1000.     speak to this STDWIN server.
  1001.  
  1002.     WAFE is a package that implements a symbolic interface to the Athena
  1003.     widgets (X11R5). A typical Wafe application consists in our framework
  1004.     of two parts: the front-end (we call it Wafe for Widget[Athena]front
  1005.     end) and an application program running typically as separate process.
  1006.     The application program can be implemented in an arbitrary programming
  1007.     language and talks to the front-end via stdio.  Since Wafe (the
  1008.     front-end) was developed using the extensible TCL shell (cite John
  1009.     Ousterhout), an application program can dynamically submit requests to
  1010.     the front-end to build up the graphical user interface; the
  1011.     application can even down-load application specific procedures into
  1012.     the front-end.  The distribution contains sample application programs
  1013.     in Perl, GAWK, Prolog, TCL, and C talking to the same Wafe binary.
  1014.     Many of the demo applications are implemented in Perl.  Wafe 0.9 can
  1015.     be obtained via anonymous ftp from 
  1016.     ftp.wu-wien.ac.at:pub/src/X11/wafe-0.9.tar.Z
  1017.     (for people without name server: the ip address is 137.208.3.5)
  1018.  
  1019.     Alternatively, you could use wish from tcl. 
  1020.  
  1021.     #!/usr/local/bin/perl
  1022.     #####################################################################
  1023.     #  An example of calling wish as a subshell under Perl and
  1024.     #  interactively communicating with it through sockets.
  1025.     #
  1026.     #  The script is directly based on Gustaf Neumann's perlwafe script.
  1027.     #
  1028.     #  Dov Grobgeld dov@menora.weizmann.ac.il
  1029.     #  1993-05-17
  1030.     #####################################################################
  1031.  
  1032.     $wishbin = "/usr/local/bin/wish";
  1033.  
  1034.     die "socketpair unsuccessful: $!!\n" unless socketpair(W0,WISH,1,1,0);
  1035.     if ($pid=fork) {
  1036.         select(WISH); $| = 1;
  1037.         select(STDOUT);
  1038.  
  1039.     # Create some TCL procedures
  1040.         print WISH 'proc echo {s} {puts stdout $s; flush stdout}',"\n";
  1041.  
  1042.     # Create the widgets
  1043.     print WISH <<TCL;
  1044.     # This is a comment "inside" wish
  1045.  
  1046.     frame .f -relief raised -border 1 -bg green
  1047.     pack append . .f {top fill expand}
  1048.  
  1049.     button .f.button-pressme -text "Press me" -command {
  1050.         echo "That's nice."
  1051.     }
  1052.     button .f.button-quit -text quit -command {
  1053.         echo "quit"
  1054.     }
  1055.     pack append .f .f.button-pressme {top fill expand} \\
  1056.                .f.button-quit {top expand}
  1057.  
  1058. TCL
  1059.     ;
  1060.     # Here is the main loop which receives and sends commands
  1061.     # to wish.
  1062.     while (<WISH>) {
  1063.         chop;
  1064.         print "Wish sais: <$_>\n";
  1065.         if (/^quit/) { print WISH "destroy .\n"; last; }
  1066.     }
  1067.         wait;
  1068.     } elsif (defined $pid) {
  1069.     open(STDOUT, ">&W0");
  1070.     open(STDIN, ">&W0");
  1071.     close(W0);
  1072.     select(STDOUT); $| = 1;
  1073.     exec "$wishbin --";
  1074.     } else {
  1075.     die "fork error: $!\n";
  1076.     }
  1077.  
  1078.  
  1079.  
  1080. 1.25) What is perl4?  What is perl5?
  1081.  
  1082.     The answer to what is perl4 is nearly anything you might otherwise 
  1083.     program in shell or C.  The answer to what is perl5 is basically
  1084.     Perl: the Next Generation.  In fact, it's essentially a complete
  1085.     rewrite of perl from the bottom up, and back again.  It's available
  1086.     in alpha form (alpha-2 now, alpha-3 soon).   The only docs for this stuff
  1087.     is what you're about to read, and what's in the t/op/ref.t file.
  1088.  
  1089.     Here are the things which are already done:
  1090.     a faster, tighter, more flexible interpreter 
  1091.  
  1092.     new token "=>" as synonym for ","; this makes 
  1093.         tables look nicer
  1094.         %T = ( OC => $red,
  1095.               TOF => "\f",
  1096.              );
  1097.         and provides for named argument passing:
  1098.         &some_func( OC => $red, TOF => "\f");
  1099.  
  1100.     recursive lists and tables:
  1101.         [a, b, [c, d], e] has 4 elts, the 3rd being itself a list
  1102.         $r->[3]->{PEANUT}; $r is a reference to a list 
  1103.                 of references to tables
  1104.  
  1105.     typed pointers (references) and generalized indirection:
  1106.         like @{$aptr} or &{$fptr} or &{ $table[$index] . "func" }().
  1107.  
  1108.     merging of list operator and function calling syntax:
  1109.         split /pat/, $string;
  1110.  
  1111.     the ref operator to find out what something is a reference to
  1112.  
  1113.     object oriented programming:
  1114.         $o->func(); # call the func member function of whatever class $o is
  1115.  
  1116.     inheritance of object types through the @ISA array
  1117.     much improved -w checking
  1118.     lexical scoping with the my operator
  1119.  
  1120.     safe global variables through package statements 
  1121.         forces variable declarations, but only if you want it
  1122.  
  1123.     per-package END functions triggered at die() or exit()
  1124.     embeddable Perl code in C code: cc prog.c -lperl 
  1125.  
  1126.     oo syntactic extensions:
  1127.         $dog->give($bone);
  1128.         is like
  1129.         give $dog $bone; 
  1130.         and 
  1131.         $STDOUT->flush(1);
  1132.         is like
  1133.         flush $STDOUT 1;  
  1134.     multiple co-resident perl interpreters: 
  1135.  
  1136.     Here is what is hoped to be done for production, but might not:
  1137.     very easy GUI Perl applications using high-level X bindings ("guiperl")
  1138.     subroutines without &'s:   myfunc($arg);
  1139.     mnemonic aliases for $<punctuation> variables
  1140.     file handle objects: $STDOUT->flush(1);
  1141.     cleanup (namespace pollution) and documentation 
  1142.         (eg. man 3pl getopt) of libraries
  1143.     addition of several new libraries (atexit, autoload, etc.)
  1144.     update h2ph and c2ph 
  1145.     misc perl development tools 
  1146.     a perl profiler
  1147.     POSIX compatibility
  1148.  
  1149.     Here is what is hope to eventually be done but very probably not in
  1150.     the first production release:
  1151.     generalization of dbm binding for assoc arrays to handle
  1152.         any generic fetch/store/open/close/flush package.
  1153.         (thus allowing both dbm and gdbm at once)
  1154.     dynamic loading of C libraries for systems that can
  1155.     byte-compiled code for speed and maybe security
  1156.  
  1157.     And here are the things that will no longer work that used to:
  1158.     open FILE || die;
  1159.     $c = shift @a + 1;
  1160.  
  1161.     It's tempting to want this stuff soon, since the sooner it comes
  1162.     out the sooner we can all build really cool applications.  But the
  1163.     longer Larry works on it, the more items from this list will actually
  1164.     get done, and the more robust the release will be.  So let's not
  1165.     ask him about it too often.  Larry says (slightly edited):
  1166.  
  1167.     I've put a tar of my current Perl 5 directory onto
  1168.     ftp.netlabs.com, in pub/outgoing/perl5.0/perl5a2.tar.Z.
  1169.  
  1170.     Now's your chance to check out all the bugs I said I fixed in
  1171.     Perl 5.  :-)
  1172.  
  1173.     Before you get all twitterpated, this is unsupported "alpha 2"
  1174.     code.  There is no Configure, only a makefile.  It will
  1175.     probably only work on a Sun4.  The compiler and interpreter are
  1176.     still very much unoptimized (though it already runs as fast or
  1177.     faster than Perl 4).  It doesn't do everything that I want it
  1178.     to yet.  It doesn't have "my" yet (though it's got the innards
  1179.     for it).  It doesn't have a debugger.
  1180.  
  1181.     Like the Alpha 1 prerelease, this is an unsupported code.  It is
  1182.     expected to work only on a Sparc architecture machine.  No
  1183.     Configure support is provided.  In fact, if you succeed in
  1184.     configuring and making a new makefile, you'll probably overwrite
  1185.     the only makefile that works.  (Note that a Sparc executable comes
  1186.     with the kit, so you may not need to compile at all.) There is
  1187.     no list of new features yet, but if you look at t/op/ref.t
  1188.     you'll see some of them in use.  perl -Dxst is also fun.
  1189.  
  1190.     But it does have references, and you can play with them.  The
  1191.     object oriented stuff is there too.  See the op/ref.t file for
  1192.     how to use them.
  1193.  
  1194.     I smell some new JAPHs coming...
  1195.  
  1196.     I don't want to get stuck "supporting" this, but if you want to
  1197.     run your favorite scripts past it and see which ones toss their
  1198.     salad, you may.  If you can come up with a decent bug report
  1199.     with a small test case, I'll certainly be glad to look at it.
  1200.     I'm not really interested in obscure core dumps at the moment.
  1201.     I'm still getting plenty of those on my own.
  1202.  
  1203.     I'm not yet interested in memory leak reports either.
  1204.  
  1205.     I can tell you that no program that uses the old autoloading
  1206.     mechanism will run, since there is no visibility into the
  1207.     symbol table pointers currently.  You ought to be able to
  1208.     redefine a subroutine while it's running, though.  (I haven't
  1209.     tested that in several months, however.  There oughta be a
  1210.     regression test for that...)
  1211.  
  1212.     Don't bother trying to diff Perl 4 with Perl 5.  Everything is
  1213.     different.  All names have been regularized.  Here's a key, if
  1214.     you're brave and want to peek at the sources:
  1215.  
  1216.         SV      scalar value
  1217.         AV      array value
  1218.         HV      hash value
  1219.         GV      glob value
  1220.         CV      code value
  1221.         RV      reference value
  1222.         PV      pointer value
  1223.         NV      numeric value
  1224.         IV      integer value
  1225.  
  1226.  
  1227. 1.26) How does Perl compare with languages like REXX or TCL?
  1228.  
  1229.     REXX is an interpreted programming language first seen on IBM systems,
  1230.     and TCL is John Ousterhout's embeddable command language.  TCL's most
  1231.     intriguing feature for many people is the tcl/tk toolset that allows
  1232.     for interpreted X-based tools.
  1233.  
  1234.     To avoid any flamage, if you really want to know the answer to this
  1235.     question, probably the best thing to do is try to write equivalent
  1236.     code to do a set of tasks.  All three have their own newsgroups in
  1237.     which you can learn about (but hopefully not argue about) these
  1238.     languages.
  1239.  
  1240.     To find out more about these or other languages, you might also check
  1241.     out David Muir Sharnoff <muir@tfs.com>'s posting on "Catalog of
  1242.     compilers, interpreters, and other language tools" which he posts to
  1243.     comp.lang.misc, comp.sources.d, comp.archives.admin, and the
  1244.     news.answers newsgroups.  It's a comprehensive treatment of many
  1245.     different languages.  (Caveat lector: he considers Perl's syntax
  1246.     "unappealing".)   This list is archived on convex.com in 
  1247.     /pub/perl/info/lang-survey.shar .
  1248.  
  1249.  
  1250. 1.27) Is it a Perl program or a Perl script?
  1251.  
  1252.     Certainly. :-)
  1253.  
  1254.     Current UNIX parlance holds that anything interpreted
  1255.     is a script, and anything compiled into native machine
  1256.     code is a program.  However, others hold that a program
  1257.     is a program is a program: after all, one seldom discusses
  1258.     scripts written in BASIC or LISP.  Larry considers it
  1259.     a program if it's set in stone and you can't change it,
  1260.     whereas if you go in and hack on it, then it's a script.
  1261.  
  1262.     But doesn't really matter.  The terms are generally 
  1263.     interchangeable today.
  1264.  
  1265.  
  1266. 1.28) What's the difference between "Perl" and "perl"?
  1267.  
  1268.      32 :-)  [  ord('p') - ord('P')  ]
  1269.  
  1270.      Larry now uses "Perl" to signify the language proper and "perl" the
  1271.      implementation of it, i.e. the current interpreter.  Hence tchrist's quip
  1272.      that "Nothing but perl can parse Perl."
  1273.  
  1274.      On the other hand, the aesthetic value of casewise parallelism
  1275.      in "awk", "sed", and "perl" as much require the lower-case 
  1276.      version as "C", "Pascal", and "Perl" require the 
  1277.      upper-case version.  It's also easier to type "Perl" in 
  1278.      typeset print than to be constantly switching in Courier. :-)
  1279.     
  1280.      In other words, it doesn't matter much, especially if all
  1281.      you're doing is hearing someone talk about the language;
  1282.      case is hard to distinguish aurally.
  1283.  
  1284.  
  1285. 1.29) What companies use or ship Perl?
  1286.  
  1287.     At this time, the known list of companies that ship Perl includes at
  1288.     least the following, although some have snuck it into /usr/contrib
  1289.     or its moral equivalent:
  1290.  
  1291.     BSDI
  1292.     Comdisco Systems
  1293.     CONVEX Computer Corporation
  1294.     Crosspoint Solutions
  1295.     Dell
  1296.     DRD Corporation
  1297.     Intergraph
  1298.     Kubota Pacific 
  1299.     Netlabs
  1300.     Univel
  1301.  
  1302.     Furthermore, the following vendors are reported to begin shipping perl
  1303.     standard with their systems in the very near future:
  1304.  
  1305.     Sun
  1306.     SGI
  1307.  
  1308.     Some companies ship it on their "User Contributed Software Tape",
  1309.     such as DEC and HP.  Apple Computer has shipped the MPW version of
  1310.     Macintosh Perl on one of their Developer CDs (Essentials*Tools*Objects 
  1311.     #11) (and they included it under "Essentials" :-)
  1312.  
  1313.     Many other companies use Perl internally for purposes of tools
  1314.     development, systems administration, installation scripts, and test
  1315.     suites.  Rumor has it that the large workstation vendors (the TLA set)
  1316.     are seriously looking into shipping Perl with their standard systems
  1317.     "soon".
  1318.  
  1319.     People with support contracts with their vendors are actively 
  1320.     encouraged to submit enhancement requests that Perl be shipped 
  1321.     as part of their standard system.  It would, at the very least,
  1322.     reduce the FTP load on the Internet. :-)
  1323.  
  1324.     If you know of any others, please send them in.
  1325.  
  1326.  
  1327. 1.30) Is there commercial, 3rd-party support for Perl?
  1328.  
  1329.     Not really.  Although perl is included in the GNU distribution, at
  1330.     last check, Cygnus does not offer support for it.  However, it's
  1331.     unclear whether they've ever been offered sufficient financial
  1332.     incentive to do so.
  1333.  
  1334.     On the other hand, you do have comp.lang.perl as a totally gratis
  1335.     support mechanism.  As long as you ask "interesting" questions, 
  1336.     you'll probably get plenty of help. :-)
  1337.  
  1338.     While some vendors do ship Perl with their platforms, that doesn't
  1339.     mean they support it on arbitrary other platforms.  And in fact, all
  1340.     they'll probably do is forward any bug reports on to Larry.  In
  1341.     practice, this is far better support than you could hope for from
  1342.     nearly any vendor.
  1343.  
  1344.     The companies who won't use something unless they can pay money
  1345.     for it will be left out.  Often they're motivated by wanting 
  1346.     someone whom they could sue.  If all they want is someone to help
  1347.     them out with Perl problems, there's always the net.  And if they
  1348.     really want to pay someone for that help, well, Tom and Randal are
  1349.     always looking for a job. :-)
  1350.  
  1351.     If companies want "commercial support" for it badly enough, speak
  1352.     up -- something might be able to be arranged.
  1353.  
  1354.  
  1355. 1.31) Where can I get a list of the JAPH signature quotes?
  1356.  
  1357.     These are the "just another perl hacker" signatures that
  1358.     some people sign their postings with.  About 100 of the 
  1359.     of the earlier ones are on convex.com in /pub/perl/info/japh.
  1360.  
  1361. 1.32) Where can I get a list of Larry Wall witticisms?
  1362.  
  1363.     Over a hundred quips by Larry, from postings of his or source code,
  1364.     can be found on convex.com in /pub/perl/info/lwall-quotes.  
  1365.  
  1366. 1.33) Is there a pretty-printer for Perl?
  1367.  
  1368.     That depends on what you mean.  If you want something 
  1369.     that works like vgrind on Perl programs, then the answer
  1370.     is "yes, nearly".  Here's a vgrind entry for perl:
  1371.  
  1372.     PERL|perl|Perl:\
  1373.         :pb=^\d?(sub|package)\d\p\d:\
  1374.         :bb={:be=}:cb=#:ce=$:sb=":se=\e":lb=':\
  1375.         :le=\e':tl:\
  1376.         :id=_:\
  1377.         :kw=\
  1378.         if for foreach unless until while continue else elsif \
  1379.         do eval require \
  1380.         die exit \
  1381.         defined delete reset \
  1382.         goto last redo next dump \
  1383.         local undef return  \
  1384.         write format  \
  1385.         sub package
  1386.  
  1387.     It doesn't actually do everything right; in particular, 
  1388.     things like $#, $', s#/foo##, and $foo'bar all confuse it.
  1389.  
  1390.     David Levine uses this:
  1391.  
  1392.     # perl 4.x                        David Levine <levine@ics.uci.edu> 05 apr 1993
  1393.     # Derived from Tom  Christiansen's perl vgrindef.   I'd  like to  treat all  of
  1394.     # perl's  built-ins  as   keywords,  but  vgrind   fields are  limited  to 1024
  1395.     # characters   and  the built-ins  overflow that  (surprise  :-).  So, I didn't
  1396.     # include  the dbm*,  end*, get*,  msg*,  sem*, set*,  and  shm* functions.   I
  1397.     # couldn't come  up  with an easy   way to  distinguish beginnings  of literals
  1398.     # ('...') from package prefixes, so literals are not marked.
  1399.     # Be sure to:
  1400.     # 1) include whitespace between a subprogram name and its opening {
  1401.     # 2) include whitespace before a comment (so that $# doesn't get interpreted as
  1402.     #    one).
  1403.     perl4:\
  1404.         :pb=^\d?(sub|package)\d\p\d:\
  1405.         :id=$%@_:\
  1406.         :bb=\e{:be=\e}:cb=\d\e#:ce=$:sb=\e":se=\e":\
  1407.         :kw=accept alarm atan2 bind binmode caller chdir chmod chop chown \
  1408.     chroot close closedir connect continue cos crypt defined delete die do dump \
  1409.     each else elsif eof eval exec exit exp fcntl fileno flock for foreach fork \
  1410.     format getc gmtime goto grep hex if include index int ioctl join keys kill \
  1411.     last length link listen local localtime log lstat m mkdir next oct open \
  1412.     opendir ord pack package pipe pop print printf push q qq qx rand read readdir \
  1413.     readlink recv redo rename require reset return reverse rewinddir rindex rmdir \
  1414.     s scalar seek seekdir select send shift shutdown sin sleep socket socketpair \
  1415.     sort splice split sprintf sqrt srand stat study sub substr symlink syscall \
  1416.     sysread system syswrite tell telldir time times tr truncate umask undef \
  1417.     unless unlink unpack unshift until utime values vec wait waitpid wantarray \
  1418.     warn while write y:
  1419.  
  1420.     If what you mean is whether there is a program that will
  1421.     reformat the program much as indent(1) will do for C, then
  1422.     the answer is no.  The complex feedback between the scanner
  1423.     and the parser (as in the things that confuse vgrind) make
  1424.     it challenging at best to write a stand-alone C parser.
  1425.  
  1426. 1.34) Can I dynamically load C user routines?
  1427.  
  1428.     Yes, kinda.  One package has been released that does this, by
  1429.     Roberto Salama <rs@fi.gs.com>.  He writes:
  1430.  
  1431.     Here is a version of dylperl, dynamic linker for perl. The code here
  1432.     is based on Oliver Sharp's May 1993 article in Dr. Dobbs Journal
  1433.     (Dynamic Linking under Berkeley UNIX).
  1434.  
  1435.           dyl.h 
  1436.           dyl.c - code extracted from Oliver Sharp's article
  1437.  
  1438.           hash.h
  1439.           hash.c - Berkeley's hash functions, should use perl's but could not
  1440.                be bothered
  1441.  
  1442.        dylperl.c - perl usersubs
  1443.           user.c - userinit function
  1444.  
  1445.         sample.c - sample code to be dyl'ed
  1446.        sample2.c -          "
  1447.          test.pl - sample perl script that dyl's sample*.o
  1448.  
  1449.     The Makefile assumes that uperl.o is in /usr/local/src/perl/... You
  1450.     will probable have to change this to reflect your installation. Other
  1451.     than that, just type 'make'...
  1452.  
  1453.     The idea behind being able to dynamnically link code into perl is that
  1454.     the linked code should become perl functions, i.e. they can be invoked
  1455.     as &foo(...).  For this to happen, the incrementally code must use the
  1456.     perl stack, look at sample.c to get a better idea.
  1457.  
  1458.     The few functions that make up this package are outlined below.
  1459.  
  1460.     &dyl("file.o"): dynamically link file.o. All functions and non-static
  1461.            variables become visible from within perl. This
  1462.            function returns a pointer to an internal hash table
  1463.            corresponding to the symbol table of the newly loaded
  1464.            code.
  1465.  
  1466.            eg: $ht = &dyl("sample.o")
  1467.  
  1468.            This function can also be called with the -L and -l ld options.
  1469.  
  1470.            eg: $ht = &dyl(""sample2.o", "-L/usr/lib", "-lm")
  1471.                will also pick up the math library if sample.o
  1472.                accesses any symbols there.
  1473.  
  1474.     &dyl_find("func"): find symbol 'func' and return its symbol table entry
  1475.  
  1476.     &dyl_functions($ht): print the contents of the internal hash table
  1477.     &dyl_print_symbols($f): prints the contents of the symbol returned by dyl_find()
  1478.  
  1479.     There is very little documentation, maybe something to do for a future
  1480.     release.  The files sample.o, and sample2.o contain code to be
  1481.     incrementally loaded, test.pl is the test perl script.
  1482.  
  1483.     Comments are welcome. I submit this code for public consumption and,
  1484.     basically, am not responsible for it in any way.
  1485.  
  1486. -------------------------------------------------------------------------------
  1487. -------------------------------------------------------------------------------
  1488.  
  1489.  
  1490. This section contains answers to the following technical questions
  1491. regarding Perl:
  1492.  
  1493.  
  1494. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  1495.  
  1496.     Those are type specifiers: $ for scalar values, @ for indexed arrays,
  1497.     and % for hashed arrays.  The * means all types of that symbol name
  1498.     and are sometimes used like pointers; the <> are used for inputting
  1499.     a record from a filehandle.  See the question on arrays of arrays
  1500.     for more about Perl pointers.
  1501.  
  1502.     Always make sure to use a $ for single values and @ for multiple ones.
  1503.     Thus element 2 of the @foo array is accessed as $foo[2], not @foo[2],
  1504.     which is a list of length one (not a scalar), and is a fairly common
  1505.     novice mistake.  Sometimes you can get by with @foo[2], but it's
  1506.     not really doing what you think it's doing for the reason you think
  1507.     it's doing it, which means one of these days, you'll shoot yourself
  1508.     in the foot; ponder for a moment what these will really do:
  1509.     @foo[0] = `cmd args`;
  1510.     @foo[2] = <FILE>;
  1511.     Just always say $foo[2] and you'll be happier.
  1512.  
  1513.     This may seem confusing, but try to think of it this way:  you use the
  1514.     character of the type which you *want back*.  You could use @foo[1..3] for
  1515.     a slice of three elements of @foo, or even @foo{A,B,C} for a slice of
  1516.     of %foo.  This is the same as using ($foo[1], $foo[2], $foo[3]) and
  1517.     ($foo{A}, $foo{B}, $foo{C}) respectively.  In fact, you can even use
  1518.     lists to subscript arrays and pull out more lists, like @foo[@bar] or
  1519.     @foo{@bar}, where @bar is in both cases presumably a list of subscripts.
  1520.  
  1521.     While there are a few places where you don't actually need these type
  1522.     specifiers, except for files, you should always use them.  Note that
  1523.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  1524.     getline function, that is, it reads a line from the handle FILE.  When
  1525.     doing open, close, and other operations besides the getline function on
  1526.     files, do NOT use the brackets.
  1527.  
  1528.     Beware of saying:
  1529.     $foo = BAR;
  1530.     Which wil be interpreted as 
  1531.     $foo = 'BAR';
  1532.     and not as 
  1533.     $foo = <BAR>;
  1534.     If you always quote your strings, you'll avoid this trap.
  1535.  
  1536.     Normally, files are manipulated something like this (with appropriate
  1537.     error checking added if it were production code):
  1538.  
  1539.     open (FILE, ">/tmp/foo.$$");
  1540.     print FILE "string\n";
  1541.     close FILE;
  1542.  
  1543.     If instead of a filehandle, you use a normal scalar variable with file
  1544.     manipulation functions, this is considered an indirect reference to a
  1545.     filehandle.  For example,
  1546.  
  1547.     $foo = "TEST01";
  1548.     open($foo, "file");
  1549.  
  1550.     After the open, these two while loops are equivalent:
  1551.  
  1552.     while (<$foo>) {}
  1553.     while (<TEST01>) {}
  1554.  
  1555.     as are these two statements:
  1556.     
  1557.     close $foo;
  1558.     close TEST01;
  1559.  
  1560.     but NOT to this:
  1561.  
  1562.     while (<$TEST01>) {} # error
  1563.         ^
  1564.         ^ note spurious dollar sign
  1565.  
  1566.     This is another common novice mistake; often it's assumed that
  1567.  
  1568.     open($foo, "output.$$");
  1569.  
  1570.     will fill in the value of $foo, which was previously undefined.  
  1571.     This just isn't so -- you must set $foo to be the name of a valid
  1572.     filehandle before you attempt to open it.
  1573.  
  1574.  
  1575. 2.2) Why don't backticks work as they do in shells?  
  1576.  
  1577.     Several reason.  One is because backticks do not interpolate within
  1578.     double quotes in Perl as they do in shells.  
  1579.     
  1580.     Let's look at two common mistakes:
  1581.  
  1582.          $foo = "$bar is `wc $file`";  # WRONG
  1583.  
  1584.     This should have been:
  1585.  
  1586.      $foo = "$bar is " . `wc $file`;
  1587.  
  1588.     But you'll have an extra newline you might not expect.  This
  1589.     does not work as expected:
  1590.  
  1591.       $back = `pwd`; chdir($somewhere); chdir($back); # WRONG
  1592.  
  1593.     Because backticks do not automatically eat trailing or embedded
  1594.     newlines.  The chop() function will remove the last character from
  1595.     a string.  This should have been:
  1596.  
  1597.       chop($back = `pwd`); chdir($somewhere); chdir($back);
  1598.  
  1599.     You should also be aware that while in the shells, embedding
  1600.     single quotes will protect variables, in Perl, you'll need 
  1601.     to escape the dollar signs.
  1602.  
  1603.     Shell: foo=`cmd 'safe $dollar'`
  1604.     Perl:  $foo=`cmd 'safe \$dollar'`;
  1605.     
  1606.  
  1607. 2.3) How come Perl operators have different precedence than C operators?
  1608.  
  1609.     Actually, they don't; all C operators have the same precedence in Perl as
  1610.     they do in C.  The problem is with a class of functions called list
  1611.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  1612.     bizarre in that they have different precedence depending on whether you
  1613.     look on the left or right of them.  Basically, they gobble up all things
  1614.     on their right.  For example,
  1615.  
  1616.     unlink $foo, "bar", @names, "others";
  1617.  
  1618.     will unlink all those file names.  A common mistake is to write:
  1619.  
  1620.     unlink "a_file" || die "snafu";
  1621.  
  1622.     The problem is that this gets interpreted as
  1623.  
  1624.     unlink("a_file" || die "snafu");
  1625.  
  1626.     To avoid this problem, you can always make them look like function calls
  1627.     or use an extra level of parentheses:
  1628.  
  1629.     (unlink "a_file") || die "snafu";
  1630.     unlink("a_file")  || die "snafu";
  1631.  
  1632.     Sometimes you actually do care about the return value:
  1633.  
  1634.     unless ($io_ok = print("some", "list")) { } 
  1635.  
  1636.     Yes, print() return I/O success.  That means
  1637.  
  1638.     $io_ok = print(2+4) * 5;
  1639.  
  1640.     returns 5 times whether printing (2+4) succeeded, and 
  1641.     print(2+4) * 5;
  1642.     returns the same 5*io_success value and tosses it.
  1643.  
  1644.     See the Perl man page's section on Precedence for more gory details,
  1645.     and be sure to use the -w flag to catch things like this.
  1646.  
  1647.  
  1648. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  1649.  
  1650.     The natural way to program in those languages may not make for the fastest
  1651.     Perl code.  Notably, the awk-to-perl translator produces sub-optimal code;
  1652.     see the a2p man page for tweaks you can make.
  1653.  
  1654.     Two of Perl's strongest points are its associative arrays and its regular
  1655.     expressions.  They can dramatically speed up your code when applied
  1656.     properly.  Recasting your code to use them can help a lot.
  1657.  
  1658.     How complex are your regexps?  Deeply nested sub-expressions with {n,m} or
  1659.     * operators can take a very long time to compute.  Don't use ()'s unless
  1660.     you really need them.  Anchor your string to the front if you can.
  1661.  
  1662.     Something like this:
  1663.     next unless /^.*%.*$/; 
  1664.     runs more slowly than the equivalent:
  1665.     next unless /%/;
  1666.  
  1667.     Note that this:
  1668.     next if /Mon/;
  1669.     next if /Tue/;
  1670.     next if /Wed/;
  1671.     next if /Thu/;
  1672.     next if /Fri/;
  1673.     runs faster than this:
  1674.     next if /Mon/ || /Tue/ || /Wed/ || /Thu/ || /Fri/;
  1675.     which in turn runs faster than this:
  1676.     next if /Mon|Tue|Wed|Thu|Fri/;
  1677.     which runs *much* faster than:
  1678.     next if /(Mon|Tue|Wed|Thu|Fri)/;
  1679.  
  1680.     There's no need to use /^.*foo.*$/ when /foo/ will do.
  1681.  
  1682.     Remember that a printf costs more than a simple print.
  1683.  
  1684.     Don't split() every line if you don't have to.
  1685.  
  1686.     Another thing to look at is your loops.  Are you iterating through 
  1687.     indexed arrays rather than just putting everything into a hashed 
  1688.     array?  For example,
  1689.  
  1690.     @list = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stv');
  1691.  
  1692.     for $i ($[ .. $#list) {
  1693.         if ($pattern eq $list[$i]) { $found++; } 
  1694.     } 
  1695.  
  1696.     First of all, it would be faster to use Perl's foreach mechanism
  1697.     instead of using subscripts:
  1698.  
  1699.     foreach $elt (@list) {
  1700.         if ($pattern eq $elt) { $found++; } 
  1701.     } 
  1702.  
  1703.     Better yet, this could be sped up dramatically by placing the whole
  1704.     thing in an associative array like this:
  1705.  
  1706.     %list = ('abc', 1, 'def', 1, 'ghi', 1, 'jkl', 1, 
  1707.          'mno', 1, 'pqr', 1, 'stv', 1 );
  1708.     $found += $list{$pattern};
  1709.     
  1710.     (but put the %list assignment outside of your input loop.)
  1711.  
  1712.     You should also look at variables in regular expressions, which is
  1713.     expensive.  If the variable to be interpolated doesn't change over the
  1714.     life of the process, use the /o modifier to tell Perl to compile the
  1715.     regexp only once, like this:
  1716.  
  1717.     for $i (1..100) {
  1718.         if (/$foo/o) {
  1719.         &some_func($i);
  1720.         } 
  1721.     } 
  1722.  
  1723.     Finally, if you have a bunch of patterns in a list that you'd like to 
  1724.     compare against, instead of doing this:
  1725.  
  1726.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  1727.     foreach $pat (@pats) {
  1728.         if ( $name =~ /^$pat$/ ) {
  1729.         &some_func();
  1730.         last;
  1731.         }
  1732.     }
  1733.  
  1734.     If you build your code and then eval it, it will be much faster.
  1735.     For example:
  1736.  
  1737.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  1738.     $code = <<EOS
  1739.         while (<>) { 
  1740.             study;
  1741. EOS
  1742.     foreach $pat (@pats) {
  1743.         $code .= <<EOS
  1744.         if ( /^$pat\$/ ) {
  1745.             &some_func();
  1746.             next;
  1747.         }
  1748. EOS
  1749.     }
  1750.     $code .= "}\n";
  1751.     print $code if $debugging;
  1752.     eval $code;
  1753.  
  1754.  
  1755.  
  1756. 2.5) How can I call my system's unique C functions from Perl?
  1757.  
  1758.     If these are system calls and you have the syscall() function, then
  1759.     you're probably in luck -- see the next question.  For arbitrary
  1760.     library functions, it's not quite so straight-forward.  While you
  1761.     can't have a C main and link in Perl routines, if you're
  1762.     determined, you can extend Perl by linking in your own C routines.
  1763.     See the usub/ subdirectory in the Perl distribution kit for an example
  1764.     of doing this to build a Perl that understands curses functions.  It's
  1765.     neither particularly easy nor overly-documented, but it is feasible.
  1766.  
  1767.  
  1768. 2.6) Where do I get the include files to do ioctl() or syscall()?
  1769.  
  1770.     These are generated from your system's C include files using the h2ph
  1771.     script (once called makelib) from the Perl source directory.  This will
  1772.     make files containing subroutine definitions, like &SYS_getitimer, which
  1773.     you can use as arguments to your function.
  1774.  
  1775.     You might also look at the h2pl subdirectory in the Perl source for how to
  1776.     convert these to forms like $SYS_getitimer; there are both advantages and
  1777.     disadvantages to this.  Read the notes in that directory for details.  
  1778.    
  1779.     In both cases, you may well have to fiddle with it to make these work; it
  1780.     depends how funny-looking your system's C include files happen to be.
  1781.  
  1782.     If you're trying to get at C structures, then you should take a look
  1783.     at using c2ph, which uses debugger "stab" entries generated by your
  1784.     BSD or GNU C compiler to produce machine-independent perl definitions
  1785.     for the data structures.  This allows to you avoid hardcoding
  1786.     structure layouts, types, padding, or sizes, greatly enhancing
  1787.     portability.  c2ph comes with the perl distribution.  On an SCO
  1788.     system, GCC only has COFF debugging support by default, so you'll have
  1789.     to build GCC 2.1 with DBX_DEBUGGING_INFO defined, and use -gstabs to
  1790.     get c2ph to work there.
  1791.  
  1792.     See the file /pub/perl/info/ch2ph on convex.com via anon ftp 
  1793.     for more traps and tips on this process.
  1794.  
  1795.  
  1796. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  1797.  
  1798.     Well, it does.  The thing to remember is that local() provides an array
  1799.     context, and that the <FILE> syntax in an array context will read all the
  1800.     lines in a file.  To work around this, use:
  1801.  
  1802.     local($foo);
  1803.     $foo = <FILE>;
  1804.  
  1805.     You can use the scalar() operator to cast the expression into a scalar
  1806.     context:
  1807.  
  1808.     local($foo) = scalar(<FILE>);
  1809.  
  1810.  
  1811. 2.8) How can I detect keyboard input without reading it? 
  1812.  
  1813.     You should check out the Frequently Asked Questions list in
  1814.     comp.unix.* for things like this: the answer is essentially the same.
  1815.     It's very system dependent.  Here's one solution that works on BSD
  1816.     systems:
  1817.  
  1818.     sub key_ready {
  1819.         local($rin, $nfd);
  1820.         vec($rin, fileno(STDIN), 1) = 1;
  1821.         return $nfd = select($rin,undef,undef,0);
  1822.     }
  1823.  
  1824.  
  1825. 2.9) How can I read a single character from the keyboard under UNIX and DOS?
  1826.  
  1827.     A closely related question to the no-echo question is how to input a
  1828.     single character from the keyboard.  Again, this is a system dependent
  1829.     operation.  The following code that may or may not help you.  It should
  1830.     work on both SysV and BSD flavors of UNIX:
  1831.  
  1832.     $BSD = -f '/vmunix';
  1833.     if ($BSD) {
  1834.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  1835.     }
  1836.     else {
  1837.         system "stty", '-icanon',
  1838.         system "stty", 'eol', "\001"; 
  1839.     }
  1840.  
  1841.     $key = getc(STDIN);
  1842.  
  1843.     if ($BSD) {
  1844.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  1845.     }
  1846.     else {
  1847.         system "stty", 'icanon';
  1848.         system "stty", 'eol', '^@'; # ascii null
  1849.     }
  1850.     print "\n";
  1851.  
  1852.     You could also handle the stty operations yourself for speed if you're
  1853.     going to be doing a lot of them.  This code works to toggle cbreak
  1854.     and echo modes on a BSD system:
  1855.  
  1856.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  1857.     local($on) = $_[0];
  1858.     local($sgttyb,@ary);
  1859.     require 'sys/ioctl.ph';
  1860.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  1861.  
  1862.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  1863.  
  1864.     @ary = unpack($sgttyb_t,$sgttyb);
  1865.     if ($on) {
  1866.         $ary[4] |= &CBREAK;
  1867.         $ary[4] &= ~&ECHO;
  1868.     } else {
  1869.         $ary[4] &= ~&CBREAK;
  1870.         $ary[4] |= &ECHO;
  1871.     }
  1872.     $sgttyb = pack($sgttyb_t,@ary);
  1873.  
  1874.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  1875.     }
  1876.  
  1877.     Note that this is one of the few times you actually want to use the
  1878.     getc() function; it's in general way too expensive to call for normal
  1879.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  1880.     or sysread() functions.
  1881.  
  1882.     For perspectives on more portable solutions, use anon ftp to retrieve
  1883.     the file /pub/perl/info/keypress from convex.com.
  1884.  
  1885.     For DOS systems, Dan Carson <dbc@tc.fluke.COM> reports:
  1886.  
  1887.     To put the PC in "raw" mode, use ioctl with some magic numbers gleaned
  1888.     from msdos.c (Perl source file) and Ralf Brown's interrupt list (comes
  1889.     across the net every so often):
  1890.  
  1891.     $old_ioctl = ioctl(STDIN,0,0);     # Gets device info
  1892.     $old_ioctl &= 0xff;
  1893.     ioctl(STDIN,1,$old_ioctl | 32);    # Writes it back, setting bit 5
  1894.  
  1895.     Then to read a single character:
  1896.  
  1897.     sysread(STDIN,$c,1);               # Read a single character
  1898.  
  1899.     And to put the PC back to "cooked" mode:
  1900.  
  1901.     ioctl(STDIN,1,$old_ioctl);         # Sets it back to cooked mode.
  1902.  
  1903.  
  1904.     So now you have $c.  If ord($c) == 0, you have a two byte code, which
  1905.     means you hit a special key.  Read another byte (sysread(STDIN,$c,1)),
  1906.     and that value tells you what combination it was according to this
  1907.     table:
  1908.  
  1909.     # PC 2-byte keycodes = ^@ + the following:
  1910.  
  1911.     # HEX     KEYS
  1912.     # ---     ----
  1913.     # 0F      SHF TAB
  1914.     # 10-19   ALT QWERTYUIOP
  1915.     # 1E-26   ALT ASDFGHJKL
  1916.     # 2C-32   ALT ZXCVBNM
  1917.     # 3B-44   F1-F10
  1918.     # 47-49   HOME,UP,PgUp
  1919.     # 4B      LEFT
  1920.     # 4D      RIGHT
  1921.     # 4F-53   END,DOWN,PgDn,Ins,Del
  1922.     # 54-5D   SHF F1-F10
  1923.     # 5E-67   CTR F1-F10
  1924.     # 68-71   ALT F1-F10
  1925.     # 73-77   CTR LEFT,RIGHT,END,PgDn,HOME
  1926.     # 78-83   ALT 1234567890-=
  1927.     # 84      CTR PgUp
  1928.  
  1929.     This is all trial and error I did a long time ago, I hope I'm reading the
  1930.     file that worked.
  1931.  
  1932.  
  1933. 2.10) How can I make an array of arrays or other recursive data types?
  1934.  
  1935.     Remember that Perl isn't about nested data structures (actually,
  1936.     perl0 ..  perl4 weren't, but maybe perl5 will be, at least
  1937.     somewhat).  It's about flat ones, so if you're trying to do this, you
  1938.     may be going about it the wrong way or using the wrong tools.  You
  1939.     might try parallel arrays with common subscripts.
  1940.  
  1941.     But if you're bound and determined, you can use the multi-dimensional
  1942.     array emulation of $a{'x','y','z'}, or you can make an array of names
  1943.     of arrays and eval it.
  1944.  
  1945.     For example, if @name contains a list of names of arrays, you can 
  1946.     get at a the j-th element of the i-th array like so:
  1947.  
  1948.     $ary = $name[$i];
  1949.     $val = eval "\$$ary[$j]";
  1950.  
  1951.     or in one line
  1952.  
  1953.     $val = eval "\$$name[$i][\$j]";
  1954.  
  1955.     You could also use the type-globbing syntax to make an array of *name
  1956.     values, which will be more efficient than eval.  Here @name hold
  1957.     a list of pointers, which we'll have to dereference through a temporary
  1958.     variable.
  1959.  
  1960.     For example:
  1961.  
  1962.     { local(*ary) = $name[$i]; $val = $ary[$j]; }
  1963.  
  1964.     In fact, you can use this method to make arbitrarily nested data
  1965.     structures.  You really have to want to do this kind of thing
  1966.     badly to go this far, however, as it is notationally cumbersome.
  1967.  
  1968.     Let's assume you just simply *have* to have an array of arrays of
  1969.     arrays.  What you do is make an array of pointers to arrays of
  1970.     pointers, where pointers are *name values described above.  You
  1971.     initialize the outermost array normally, and then you build up your
  1972.     pointers from there.  For example:
  1973.  
  1974.     @w = ( 'ww' .. 'xx' );
  1975.     @x = ( 'xx' .. 'yy' );
  1976.     @y = ( 'yy' .. 'zz' );
  1977.     @z = ( 'zz' .. 'zzz' );
  1978.  
  1979.     @ww = reverse @w;
  1980.     @xx = reverse @x;
  1981.     @yy = reverse @y;
  1982.     @zz = reverse @z;
  1983.  
  1984.     Now make a couple of array of pointers to these:
  1985.  
  1986.     @A = ( *w, *x, *y, *z );
  1987.     @B = ( *ww, *xx, *yy, *zz );
  1988.  
  1989.     And finally make an array of pointers to these arrays:
  1990.  
  1991.     @AAA = ( *A, *B );
  1992.  
  1993.     To access an element, such as AAA[i][j][k], you must do this:
  1994.  
  1995.     local(*foo) = $AAA[$i];
  1996.     local(*bar) = $foo[$j];
  1997.     $answer = $bar[$k];
  1998.  
  1999.     Similar manipulations on associative arrays are also feasible.
  2000.  
  2001.     You could take a look at recurse.pl package posted by Felix Lee
  2002.     <flee@cs.psu.edu>, which lets you simulate vectors and tables (lists and
  2003.     associative arrays) by using type glob references and some pretty serious
  2004.     wizardry.
  2005.  
  2006.     In C, you're used to creating recursive datatypes for operations
  2007.     like recursive decent parsing or tree traversal.  In Perl, these
  2008.     algorithms are best implemented using associative arrays.  Take an
  2009.     array called %parent, and build up pointers such that $parent{$person}
  2010.     is the name of that person's parent.  Make sure you remember that
  2011.     $parent{'adam'} is 'adam'. :-) With a little care, this approach can
  2012.     be used to implement general graph traversal algorithms as well.
  2013.  
  2014.     In Perl5, it's quite easy to declare these things.  For example
  2015.  
  2016.     @A = (
  2017.         [ 'ww' .. 'xx'  ], 
  2018.         [ 'xx' .. 'yy'  ], 
  2019.         [ 'yy' .. 'zz'  ], 
  2020.         [ 'zz' .. 'zzz' ], 
  2021.     );
  2022.  
  2023.     And now reference $A[2]->[0] to pull out "yy".  These may also nest
  2024.     and mix with tables:
  2025.  
  2026.     %T = (
  2027.         key0, { k0, v0, k1, v1 },    
  2028.         key1, { k2, v2, k3, v3 },    
  2029.         key2, { k2, v2, k3, [ 0, 'a' .. 'z' ] },    
  2030.     );
  2031.     
  2032.     Allosing you to reference $T{key2}->{k3}->[3] to pull out 'c'.
  2033.  
  2034.  
  2035.  
  2036. 2.11) How do I make an array of structures containing various data types?
  2037.  
  2038.     Well, soon you may not have to, but for now, let's look at ways to 
  2039.     synthesize these.
  2040.  
  2041.     One scheme I've invented uses what I call pseudoanonymous packages.
  2042.     This was motivated because I wanted an associative array of structures
  2043.     in which each structure contained not merely scalar data, but also lists
  2044.     and tables.   
  2045.  
  2046.     The table (read: associative array) is called %Active_Folders, whose
  2047.     key is the name of the folder, and whose values are, well, *logically*
  2048.     they're each a structure whose components look like this:
  2049.  
  2050.     $Current_Folder
  2051.     $Current_Seq  
  2052.     $Current_Line
  2053.     $Top_Line   
  2054.     $Incomplete_Read    
  2055.     $Folder_ID  
  2056.     $Last_Typed 
  2057.     @Scan_Lines
  2058.     %Scan_IDs 
  2059.     %Deleted 
  2060.  
  2061.     The way it works is that I only have one folder active at once.
  2062.     Those symbols as listed above are accessible from anywhere in the
  2063.     program.  The trick is that when I want to switch folders, I change
  2064.     what they point to!  You see, there's a package for each folder name
  2065.     that contains the real data.  So, it's not like I get to dereference
  2066.  
  2067.     $Active_Folder{$foldername}->$Current_Line
  2068.  
  2069.     or 
  2070.     $Active_Folder{$foldername}->$Scan_IDs{$msgnum}
  2071.  
  2072.     Although I'd like to.  I have to switch folders to $foldername first,
  2073.     and then access the individual fields directly.  The package isn't intuitable,
  2074.     which is why it's a pseudoanonymous one.
  2075.  
  2076.     Hm, I've this scary feeling that in Perl5, the last line will really read:
  2077.  
  2078.     ${$Active_Folder{$foldername}->Scan_IDs}->{$msgnum}
  2079.  
  2080.     or something, which is truly impossible for my brain to parse.  But I'm not
  2081.     real clear on it.  I get muddled up part way through whenever Larry explains
  2082.     how multiple levels of deferencing will work, and I'm not even sure I'll be
  2083.     able to get away with the above without setting up lots of pointers first.
  2084.  
  2085.     Anyway, here's the code that allows associative arrays of structures of 
  2086.     random data types.  I haven't done more than one level yet, although 
  2087.     surely you could embed the value of $Active_Folders{$folder} as a $Prev_Folder
  2088.     field in each, then do the right appropriate thing.
  2089.  
  2090.     sub gensym { 'gensym_' . ++$gensym'symbol } 
  2091.  
  2092.     sub activate_folder {
  2093.         local($folder) = @_;
  2094.  
  2095.         &assert('$folder',$folder);
  2096.  
  2097.         $Last_Seq = $Current_Seq;
  2098.  
  2099.         if (! defined $Active_Folders{$folder}) {
  2100.         $Active_Folders{$folder} = &gensym;
  2101.         push(@Active_Folders, $folder);
  2102.         }
  2103.  
  2104.         local($package) = $Active_Folders{$folder};
  2105.  
  2106.         local($code)=<<"EOF";
  2107.         {
  2108.             package $package;
  2109.             *'Current_Folder    = *Current_Folder;
  2110.             *'Current_Seq       = *Current_Seq;
  2111.             *'Current_Line      = *Current_Line;
  2112.             *'Top_Line          = *Top_Line;
  2113.             *'Scan_Lines        = *Scan_Lines;
  2114.             *'Scan_IDs          = *Scan_IDs;
  2115.             *'Incomplete_Read   = *Incomplete_Read;
  2116.             *'Folder_ID         = *Folder_ID;
  2117.             *'Last_Typed        = *Last_Typed;
  2118.             *'Deleted           = *Deleted;
  2119.             }
  2120.         EOF
  2121.         eval $code;
  2122.         $Current_Seq = $folder;
  2123.  
  2124.         &panic("bad eval: $@\n$code\n") if $@;
  2125.     } 
  2126.  
  2127.  
  2128. 2.12) How can I quote a variable to use in a regexp?
  2129.  
  2130.     From the manual:
  2131.  
  2132.     $pattern =~ s/(\W)/\\$1/g;
  2133.  
  2134.     Now you can freely use /$pattern/ without fear of any unexpected
  2135.     meta-characters in it throwing off the search.  If you don't know
  2136.     whether a pattern is valid or not, enclose it in an eval to avoid
  2137.     a fatal run-time error.
  2138.  
  2139.  
  2140. 2.13) Why do setuid Perl scripts complain about kernel problems?
  2141.  
  2142.     This message:
  2143.  
  2144.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  2145.     FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!
  2146.  
  2147.     is triggered because setuid scripts are inherently insecure due to a
  2148.     kernel bug.  If your system has fixed this bug, you can compile Perl
  2149.     so that it knows this.  Otherwise, create a setuid C program that just
  2150.     execs Perl with the full name of the script.  Larry's wrapsuid 
  2151.     script can help.
  2152.  
  2153.  
  2154. 2.14) How do I open a pipe both to and from a command?
  2155.  
  2156.     In general, this is a dangerous move because you can find yourself in a
  2157.     deadlock situation.  It's better to put one end of the pipe to a file.
  2158.     For example:
  2159.  
  2160.     # first write some_cmd's input into a_file, then 
  2161.     open(CMD, "some_cmd its_args < a_file |");
  2162.     while (<CMD>) {
  2163.  
  2164.     # or else the other way; run the cmd
  2165.     open(CMD, "| some_cmd its_args > a_file");
  2166.     while ($condition) {
  2167.         print CMD "some output\n";
  2168.         # other code deleted
  2169.     } 
  2170.     close CMD || warn "cmd exited $?";
  2171.  
  2172.     # now read the file
  2173.     open(FILE,"a_file");
  2174.     while (<FILE>) {
  2175.  
  2176.     If you have ptys, you could arrange to run the command on a pty and
  2177.     avoid the deadlock problem.  See the chat2.pl package in the
  2178.     distributed library for ways to do this.
  2179.  
  2180.     At the risk of deadlock, it is theoretically possible to use a
  2181.     fork, two pipe calls, and an exec to manually set up the two-way
  2182.     pipe.  (BSD system may use socketpair() in place of the two pipes,
  2183.     but this is not as portable.)  The open2 library function distributed
  2184.     with the current perl release will do this for you.
  2185.  
  2186.     It assumes it's going to talk to something like adb, both writing to
  2187.     it and reading from it.  This is presumably safe because you "know"
  2188.     that commands like adb will read a line at a time and output a line at
  2189.     a time.  Programs like sort that read their entire input stream first,
  2190.     however, are quite apt to cause deadlock.
  2191.  
  2192.  
  2193. 2.15) How can I change the first N letters of a string?
  2194.  
  2195.     Remember that the substr() function produces an lvalue, that is, it may be
  2196.     assigned to.  Therefore, to change the first character to an S, you could
  2197.     do this:
  2198.  
  2199.     substr($var,0,1) = 'S';
  2200.  
  2201.     This assumes that $[ is 0;  for a library routine where you can't know $[,
  2202.     you should use this instead:
  2203.  
  2204.     substr($var,$[,1) = 'S';
  2205.  
  2206.     While it would be slower, you could in this case use a substitute:
  2207.  
  2208.     $var =~ s/^./S/;
  2209.     
  2210.     But this won't work if the string is empty or its first character is a
  2211.     newline, which "." will never match.  So you could use this instead:
  2212.  
  2213.     $var =~ s/^[^\0]?/S/;
  2214.  
  2215.     To do things like translation of the first part of a string, use substr,
  2216.     as in:
  2217.  
  2218.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  2219.  
  2220.     If you don't know then length of what to translate, something like
  2221.     this works:
  2222.  
  2223.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  2224.     
  2225.     For some things it's convenient to use the /e switch of the 
  2226.     substitute operator:
  2227.  
  2228.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  2229.  
  2230.     although in this case, it runs more slowly than does the previous example.
  2231.  
  2232.  
  2233. 2.16) How can I manipulate fixed-record-length files?
  2234.  
  2235.     The most efficient way is using pack and unpack.  This is faster than
  2236.     using substr.  Here is a sample chunk of code to break up and put back
  2237.     together again some fixed-format input lines, in this case, from ps.
  2238.  
  2239.     # sample input line:
  2240.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  2241.     $ps_t = 'A6 A4 A7 A5 A*';
  2242.     open(PS, "ps|");
  2243.     $_ = <PS>; print;
  2244.     while (<PS>) {
  2245.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  2246.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  2247.         print "$var: <", eval "\$$var", ">\n";
  2248.         }
  2249.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  2250.     }
  2251.  
  2252.  
  2253. 2.17) How can I make a file handle local to a subroutine?
  2254.  
  2255.     You must use the type-globbing *VAR notation.  Here is some code to
  2256.     cat an include file, calling itself recursively on nested local
  2257.     include files (i.e. those with #include "file", not #include <file>):
  2258.  
  2259.     sub cat_include {
  2260.         local($name) = @_;
  2261.         local(*FILE);
  2262.         local($_);
  2263.  
  2264.         warn "<INCLUDING $name>\n";
  2265.         if (!open (FILE, $name)) {
  2266.         warn "can't open $name: $!\n";
  2267.         return;
  2268.         }
  2269.         while (<FILE>) {
  2270.         if (/^#\s*include "([^"]*)"/) {
  2271.             &cat_include($1);
  2272.         } else {
  2273.             print;
  2274.         }
  2275.         }
  2276.         close FILE;
  2277.     }
  2278.  
  2279.  
  2280. 2.18) How can I extract just the unique elements of an array?
  2281.  
  2282.     There are several possible ways, depending on whether the
  2283.     array is ordered and you wish to preserve the ordering.
  2284.  
  2285.     a) If @in is sorted, and you want @out to be sorted:
  2286.  
  2287.     $prev = 'nonesuch';
  2288.     @out = grep($_ ne $prev && (($prev) = $_), @in);
  2289.  
  2290.        This is nice in that it doesn't use much extra memory, 
  2291.        simulating uniq's behavior of removing only adjacent
  2292.        duplicates.
  2293.  
  2294.     b) If you don't know whether @in is sorted:
  2295.  
  2296.     undef %saw;
  2297.     @out = grep(!$saw{$_}++, @in);
  2298.  
  2299.     c) Like (b), but @in contains only small integers:
  2300.  
  2301.     @out = grep(!$saw[$_]++, @in);
  2302.  
  2303.     d) A way to do (b) without any loops or greps:
  2304.  
  2305.     undef %saw;
  2306.     @saw{@in} = ();
  2307.     @out = sort keys %saw;  # remove sort if undesired
  2308.  
  2309.     e) Like (d), but @in contains only small positive integers:
  2310.  
  2311.     undef @ary;
  2312.     @ary[@in] = @in;
  2313.     @out = sort @ary;
  2314.  
  2315.  
  2316. 2.19) How can I call alarm() or usleep() from Perl?
  2317.  
  2318.     It's available as a built-in as of version 3.038.  If you want finer
  2319.     granularity than 1 second (as usleep() provides) and have itimers and
  2320.     syscall() on your system, you can use the following.  You could also
  2321.     use select().
  2322.  
  2323.     It takes a floating-point number representing how long to delay until
  2324.     you get the SIGALRM, and returns a floating- point number representing
  2325.     how much time was left in the old timer, if any.  Note that the C
  2326.     function uses integers, but this one doesn't mind fractional numbers.
  2327.  
  2328.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  2329.     # tom christiansen <tchrist@convex.com>
  2330.     sub alarm {
  2331.     require 'syscall.ph';
  2332.     require 'sys/time.ph';
  2333.  
  2334.     local($ticks) = @_;
  2335.     local($in_timer,$out_timer);
  2336.     local($isecs, $iusecs, $secs, $usecs);
  2337.  
  2338.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  2339.  
  2340.     $secs = int($ticks);
  2341.     $usecs = ($ticks - $secs) * 1e6;
  2342.  
  2343.     $out_timer = pack($itimer_t,0,0,0,0);  
  2344.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  2345.  
  2346.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  2347.         && die "alarm: setitimer syscall failed: $!";
  2348.  
  2349.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  2350.     return $secs + ($usecs/1e6);
  2351.     }
  2352.  
  2353.  
  2354. 2.20) How can I test whether an array contains a certain element?
  2355.  
  2356.     There are several ways to approach this.  If you are going to make
  2357.     this query many times and the values are arbitrary strings, the
  2358.     fastest way is probably to invert the original array and keep an
  2359.     associative array lying about whose keys are the first array's values.
  2360.  
  2361.     @blues = ('turquoise', 'teal', 'lapis lazuli');
  2362.     undef %is_blue;
  2363.     for (@blues) { $is_blue{$_} = 1; }
  2364.  
  2365.     Now you can check whether $is_blue{$some_color}.  It might have been
  2366.     a good idea to keep the blues all in an assoc array in the first place.
  2367.  
  2368.     If the values are all small integers, you could use a simple
  2369.     indexed array.  This kind of an array will take up less space:
  2370.  
  2371.     @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  2372.     undef @is_tiny_prime;
  2373.     for (@primes) { $is_tiny_prime[$_] = 1; }
  2374.  
  2375.     Now you check whether $is_tiny_prime[$some_number].
  2376.  
  2377.     If the values in question are integers, but instead of strings,
  2378.     you can save quite a lot of space by using bit strings instead:
  2379.  
  2380.     @articles = ( 1..10, 150..2000, 2017 );
  2381.     undef $read;
  2382.     grep (vec($read,$_,1) = 1, @articles);
  2383.     
  2384.     Now check whether vec($read,$n,1) is true for some $n.
  2385.  
  2386.  
  2387. 2.21) How can I do an atexit() or setjmp()/longjmp() in Perl?
  2388.  
  2389.     Perl's exception-handling mechanism is its eval operator.  You 
  2390.     can use eval as setjmp and die as longjmp.  Here's an example
  2391.     of Larry's for timed-out input, which in C is often implemented
  2392.     using setjmp and longjmp:
  2393.  
  2394.       $SIG{ALRM} = TIMEOUT;
  2395.       sub TIMEOUT { die "restart input\n" }
  2396.  
  2397.       do { eval { &realcode } } while $@ =~ /^restart input/;
  2398.  
  2399.       sub realcode {
  2400.           alarm 15;
  2401.           $ans = <STDIN>;
  2402.           alarm 0;
  2403.       }
  2404.  
  2405.    Here's an example of Tom's for doing atexit() handling:
  2406.  
  2407.     sub atexit { push(@_exit_subs, @_) }
  2408.  
  2409.     sub _cleanup { unlink $tmp }
  2410.  
  2411.     &atexit('_cleanup');
  2412.  
  2413.     eval <<'End_Of_Eval';  $here = __LINE__;
  2414.     # as much code here as you want
  2415.     End_Of_Eval
  2416.  
  2417.     $oops = $@;  # save error message
  2418.  
  2419.     # now call his stuff
  2420.     for (@_exit_subs) { &$_() }
  2421.  
  2422.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  2423.         " line " . ($1+$here)/e, die $oops);
  2424.  
  2425.     You can register your own routines via the &atexit function now.  You
  2426.     might also want to use the &realcode method of Larry's rather than
  2427.     embedding all your code in the here-is document.  Make sure to leave
  2428.     via die rather than exit, or write your own &exit routine and call
  2429.     that instead.   In general, it's better for nested routines to exit
  2430.     via die rather than exit for just this reason.
  2431.  
  2432.     In Perl5, it will be easy to set this up because of the automatic
  2433.     processing of per-package END functions.
  2434.  
  2435.     Eval is also quite useful for testing for system dependent features,
  2436.     like symlinks, or using a user-input regexp that might otherwise
  2437.     blowup on you.
  2438.  
  2439.  
  2440. 2.22) Why doesn't Perl interpret my octal data octally?
  2441.  
  2442.     Perl only understands octal and hex numbers as such when they occur
  2443.     as constants in your program.  If they are read in from somewhere
  2444.     and assigned, then no automatic conversion takes place.  You must
  2445.     explicitly use oct() or hex() if you want this kind of thing to happen.
  2446.     Actually, oct() knows to interpret both hex and octal numbers, while
  2447.     hex only converts hexadecimal ones.  For example:
  2448.  
  2449.     {
  2450.         print "What mode would you like? ";
  2451.         $mode = <STDIN>;
  2452.         $mode = oct($mode);
  2453.         unless ($mode) {
  2454.         print "You can't really want mode 0!\n";
  2455.         redo;
  2456.         } 
  2457.         chmod $mode, $file;
  2458.     } 
  2459.  
  2460.     Without the octal conversion, a requested mode of 755 would turn 
  2461.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  2462.  
  2463.     If you want something that handles decimal, octal and hex input, 
  2464.     you could follow the suggestion in the man page and use:
  2465.  
  2466.     $val = oct($val) if $val =~ /^0/;
  2467.  
  2468. 2.23) How do I sort an associative array by value instead of by key?
  2469.  
  2470.     You have to declare a sort subroutine to do this.  Let's assume
  2471.     you want an ASCII sort on the values of the associative array %ary.
  2472.     You could do so this way:
  2473.  
  2474.     foreach $key (sort by_value keys %ary) {
  2475.         print $key, '=', $ary{$key}, "\n";
  2476.     } 
  2477.     sub by_value { $ary{$a} cmp $ary{$b}; }
  2478.  
  2479.     If you wanted a descending numeric sort, you could do this:
  2480.  
  2481.     sub by_value { $ary{$b} <=> $ary{$a}; }
  2482.  
  2483.     You can also inline your sort function, like this, at least if 
  2484.     you have a relatively recent patchlevel of perl4:
  2485.  
  2486.     foreach $key ( sort { $ary{$b} <=> $ary{$a} } keys %ary ) {
  2487.         print $key, '=', $ary{$key}, "\n";
  2488.     } 
  2489.  
  2490.     If you wanted a function that didn't have the array name hard-wired
  2491.     into it, you could so this:
  2492.  
  2493.     foreach $key (&sort_by_value(*ary)) {
  2494.         print $key, '=', $ary{$key}, "\n";
  2495.     } 
  2496.     sub sort_by_value {
  2497.         local(*x) = @_;
  2498.         sub _by_value { $x{$a} cmp $x{$b}; } 
  2499.         sort _by_value keys %x;
  2500.     } 
  2501.  
  2502.     If you want neither an alphabetic nor a numeric sort, then you'll 
  2503.     have to code in your own logic instead of relying on the built-in
  2504.     signed comparison operators "cmp" and "<=>".
  2505.  
  2506.     Note that if you're sorting on just a part of the value, such as a
  2507.     piece you might extract via split, unpack, pattern-matching, or
  2508.     substr, then rather than performing that operation inside your sort
  2509.     routine on each call to it, it is significantly more efficient to
  2510.     build a parallel array of just those portions you're sorting on, sort
  2511.     the indices of this parallel array, and then to subscript your original
  2512.     array using the newly sorted indices.  This method works on both
  2513.     regular and associative arrays, since both @ary[@idx] and @ary{@idx}
  2514.     make sense.  See page 245 in the Camel Book on "Sorting an Array by a
  2515.     Computable Field" for a simple example of this.
  2516.  
  2517.  
  2518. 2.24) How can I capture STDERR from an external command?
  2519.  
  2520.     There are three basic ways of running external commands:
  2521.  
  2522.     system $cmd;
  2523.     $output = `$cmd`;
  2524.     open (PIPE, "cmd |");
  2525.  
  2526.     In the first case, both STDOUT and STDERR will go the same place as
  2527.     the script's versions of these, unless redirected.  You can always put
  2528.     them where you want them and then read them back when the system
  2529.     returns.  In the second and third cases, you are reading the STDOUT
  2530.     *only* of your command.  If you would like to have merged STDOUT and
  2531.     STDERR, you can use shell file-descriptor redirection to dup STDERR to
  2532.     STDOUT:
  2533.  
  2534.     $output = `$cmd 2>&1`;
  2535.     open (PIPE, "cmd 2>&1 |");
  2536.  
  2537.     Another possibility is to run STDERR into a file and read the file 
  2538.     later, as in 
  2539.  
  2540.     $output = `$cmd 2>some_file`;
  2541.     open (PIPE, "cmd 2>some_file |");
  2542.     
  2543.     Here's a way to read from both of them and know which descriptor
  2544.     you got each line from.  The trick is to pipe only STDERR through
  2545.     sed, which then marks each of its lines, and then sends that
  2546.     back into a merged STDOUT/STDERR stream, from which your Perl program
  2547.     then reads a line at a time:
  2548.  
  2549.         open (CMD, 
  2550.           "3>&1 (cmd args 2>&1 1>&3 3>&- | sed 's/^/STDERR:/' 3>&-) 3>&- |");
  2551.  
  2552.         while (<CMD>) {
  2553.           if (s/^STDERR://)  {
  2554.               print "line from stderr: ", $_;
  2555.           } else {
  2556.               print "line from stdout: ", $_;
  2557.           }
  2558.         }
  2559.  
  2560.     Be apprised that you *must* use Bourne shell redirection syntax
  2561.     here, not csh!  In fact, you can't even do these things with csh.
  2562.     For details on how lucky you are that perl's system() and backtick
  2563.     and pipe opens all use Bourne shell, fetch the file from convex.com
  2564.     called /pub/csh.whynot -- and you'll be glad that perl's shell
  2565.     interface is the Bourne shell.
  2566.  
  2567.     There's an &open3 routine out there which will be merged with 
  2568.     &open2 in perl5 production.
  2569.  
  2570.  
  2571. 2.25) Why doesn't open return an error when a pipe open fails?
  2572.  
  2573.     These statements:
  2574.  
  2575.     open(TOPIPE, "|bogus_command") || die ...
  2576.     open(FROMPIPE, "bogus_command|") || die ...
  2577.  
  2578.     will not fail just for lack of the bogus_command.  They'll only
  2579.     fail if the fork to run them fails, which is seldom the problem.
  2580.  
  2581.     If you're writing to the TOPIPE, you'll get a SIGPIPE if the child
  2582.     exits prematurely or doesn't run.  If you are reading from the
  2583.     FROMPIPE, you need to check the close() to see what happened.
  2584.  
  2585.     If you want an answer sooner than pipe buffering might otherwise
  2586.     afford you, you can do something like this:
  2587.  
  2588.     $kid = open (PIPE, "bogus_command |");   # XXX: check defined($kid)
  2589.     (kill 0, $kid) || die "bogus_command failed";
  2590.  
  2591.     This works fine if bogus_command doesn't have shell metas in it, but
  2592.     if it does, the shell may well not have exited before the kill 0.  You
  2593.     could always introduce a delay:
  2594.  
  2595.     $kid = open (PIPE, "bogus_command </dev/null |");
  2596.     sleep 1;
  2597.     (kill 0, $kid) || die "bogus_command failed";
  2598.  
  2599.     but this is sometimes undesirable, and in any event does not guarantee
  2600.     correct behavior.  But it seems slightly better than nothing.
  2601.  
  2602.     Similar tricks can be played with writable pipes if you don't wish to
  2603.     catch the SIGPIPE.
  2604.  
  2605.  
  2606. 2.26) How can I compare two date strings?
  2607.  
  2608.     If the dates are in an easily parsed, predetermined format, then you
  2609.     can break them up into their component parts and call &timelocal from
  2610.     the distributed perl library.  If the date strings are in arbitrary
  2611.     formats, however, it's probably easier to use the getdate program
  2612.     from the Cnews distribution, since it accepts a wide variety of dates.
  2613.     Note that in either case the return values you will really be
  2614.     comparing will be the total time in seconds as return by time().
  2615.    
  2616.     Here's a getdate function for perl that's not very efficient; you 
  2617.     can do better this by sending it many dates at once or modifying
  2618.     getdate to behave better on a pipe.  Beware the hardcoded pathname.
  2619.  
  2620.     sub getdate {
  2621.         local($_) = shift;
  2622.  
  2623.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  2624.         # getdate has broken timezone sign reversal!
  2625.  
  2626.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  2627.         chop;
  2628.         $_;
  2629.     } 
  2630.  
  2631.     Richard Ohnemus <rick@IMD.Sterling.COM> actually has a getdate.y
  2632.     for use with the Perl yacc.  You can get this from ftp.sterling.com
  2633.     [192.124.9.1] in /local/perl-byacc1.8.1.tar.Z, or send the author
  2634.     mail for details.
  2635.  
  2636.     You might also consider using these: 
  2637.  
  2638.     date.pl        - print dates how you want with the sysv +FORMAT method
  2639.     date.shar      - routines to manipulate and calculate dates
  2640.     ftp-chat2.shar - updated version of ftpget. includes library and demo programs
  2641.     getdate.shar   - returns number of seconds since epoch for any given date
  2642.     ptime.shar     - print dates how you want with the sysv +FORMAT method
  2643.  
  2644.     You probably want 'getdate.shar'... these and other files can be ftp'd from
  2645.     the /pub/perl/scripts directory on coombs.anu.edu.au. See the README file in
  2646.     the /pub/perl directory for time and the European mirror site details.
  2647.  
  2648.  
  2649. 2.27) What's the fastest way to code up a given task in perl?
  2650.  
  2651.     Because Perl so lends itself to a variety of different approaches
  2652.     for any given task, a common question is which is the fastest way
  2653.     to code a given task.  Since some approaches can be dramatically
  2654.     more efficient that others, it's sometimes worth knowing which is
  2655.     best.  Unfortunately, the implementation that first comes to mind,
  2656.     perhaps as a direct translation from C or the shell, often yields
  2657.     suboptimal performance.  Not all approaches have the same results
  2658.     across different hardware and software platforms.  Furthermore,
  2659.     legibility must sometimes be sacrificed for speed.
  2660.  
  2661.     While an experienced perl programmer can sometimes eye-ball the code
  2662.     and make an educated guess regarding which way would be fastest,
  2663.     surprises can still occur.  So, in the spirit of perl programming
  2664.     being an empirical science, the best way to find out which of several
  2665.     different methods runs the fastest is simply to code them all up and
  2666.     time them. For example:
  2667.  
  2668.     $COUNT = 10_000; $| = 1;
  2669.  
  2670.     print "method 1: ";
  2671.  
  2672.         ($u, $s) = times;
  2673.         for ($i = 0; $i < $COUNT; $i++) {
  2674.         # code for method 1
  2675.         }
  2676.         ($nu, $ns) = times;
  2677.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  2678.  
  2679.     print "method 2: ";
  2680.  
  2681.         ($u, $s) = times;
  2682.         for ($i = 0; $i < $COUNT; $i++) {
  2683.         # code for method 2
  2684.         }
  2685.         ($nu, $ns) = times;
  2686.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  2687.  
  2688.     For more specific tips, see the section on Efficiency in the
  2689.     ``Other Oddments'' chapter at the end of the Camel Book.
  2690.  
  2691.  
  2692. 2.28) How can I know how many entries are in an associative array?
  2693.  
  2694.     While the number of elements in a @foobar array is simply @foobar when
  2695.     used in a scalar, you can't figure out how many elements are in an
  2696.     associative array in an analogous fashion.  That's because %foobar in
  2697.     a scalar context returns the ratio (as a string) of number of buckets
  2698.     filled versus the number allocated.  For example, scalar(%ENV) might
  2699.     return "20/32".  While perl could in theory keep a count, this would
  2700.     break down on associative arrays that have been bound to dbm files.
  2701.  
  2702.     However, while you can't get a count this way, one thing you *can* use
  2703.     it for is to determine whether there are any elements whatsoever in
  2704.     the array, since "if (%table)" is guaranteed to be false if nothing
  2705.     has ever been stored in it.  
  2706.  
  2707.     So you either have to keep your own count around and increments
  2708.     it every time you store a new key in the array, or else do it
  2709.     on the fly when you really care, perhaps like this:
  2710.  
  2711.     $count++ while each %ENV;
  2712.  
  2713.     This preceding method will be faster than extracting the
  2714.     keys into a temporary array to count them.
  2715.  
  2716.     As of a very recent patch, you can say
  2717.  
  2718.     $count = keys %ENV;
  2719.  
  2720.  
  2721. 2.29) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  2722.  
  2723.     Because some stdio's set error and eof flags that need clearing.
  2724.  
  2725.     Try keeping around the seekpointer and go there, like this:
  2726.      $where = tell(LOG);
  2727.      seek(LOG, $where, 0);
  2728.  
  2729.     If that doesn't work, try seeking to a different part of the file and
  2730.     then back.  If that doesn't work, try seeking to a different part of
  2731.     the file, reading something, and then seeking back.  If that doesn't
  2732.     work, give up on your stdio package and use sysread.  You can't call
  2733.     stdio's clearerr() from Perl, so if you get EINTR from a signal
  2734.     handler, you're out of luck.  Best to just use sysread() from the
  2735.     start for the tty.
  2736.  
  2737.  
  2738. 2.30) Do I always/never have to quote my strings or use semicolons?
  2739.  
  2740.     You don't have to quote strings that can't mean anything else
  2741.     in the language, like identifiers with any upper-case letters
  2742.     in them.  Therefore, it's fine to do this:
  2743.  
  2744.     $SIG{INT} = Timeout_Routine;
  2745.     or 
  2746.  
  2747.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  2748.  
  2749.     but you can't get away with this:
  2750.  
  2751.     $foo{while} = until;
  2752.  
  2753.     in place of 
  2754.  
  2755.     $foo{'while'} = 'until';
  2756.  
  2757.     The requirements on semicolons have been increasingly relaxed.  You no
  2758.     longer need one at the end of a block, but stylistically, you're
  2759.     better to use them if you don't put the curly brace on the same line:
  2760.  
  2761.     for (1..10) { print }
  2762.  
  2763.     is ok, as is
  2764.  
  2765.     @nlist = sort { $a <=> $b } @olist;
  2766.  
  2767.     but you probably shouldn't do this:
  2768.     
  2769.     for ($i = 0; $i < @a; $i++) {
  2770.         print "i is $i\n"  # <-- oops!
  2771.     } 
  2772.  
  2773.     because you might want to add lines later, and anyway, 
  2774.     it looks funny. :-)
  2775.  
  2776.  
  2777. 2.31) How can I translate tildes in a filename?
  2778.  
  2779.     Perl doesn't expand tildes -- the shell (ok, some shells) do.
  2780.     The classic request is to be able to do something like:
  2781.  
  2782.     open(FILE, "~/dir1/file1");
  2783.     open(FILE, "~tchrist/dir1/file1");
  2784.  
  2785.     which doesn't work.  (And you don't know it, because you 
  2786.     did a system call without an "|| die" clause! :-)
  2787.  
  2788.     If you *know* you're on a system with the csh, and you *know*
  2789.     that Larry hasn't internalized file globbing, then you could
  2790.     get away with 
  2791.  
  2792.     $filename = <~tchrist/dir1/file1>;
  2793.  
  2794.     but that's pretty iffy.
  2795.  
  2796.     A better way is to do the translation yourself, as in:
  2797.  
  2798.     $filename =~ s#^~(\w+)(/.*)?$#(getpwnam($1))[7].$2#e;
  2799.  
  2800.     More robust and efficient versions that checked for error conditions,
  2801.     handed simple ~/blah notation, and cached lookups are all reasonable
  2802.     enhancements.
  2803.  
  2804.  
  2805. 2.32) How can I convert my shell script to Perl?
  2806.  
  2807.     Larry's standard answer for this is to send your script to me (Tom
  2808.     Christiansen) with appropriate supplications and offerings.  :-(
  2809.     That's because there's no automatic machine translator.  Even if you
  2810.     were, you wouldn't gain a lot, as most of the external programs would
  2811.     still get called.  It's the same problem as blind translation into C:
  2812.     you're still apt to be bogged down by exec()s.  You have to analyze
  2813.     the dataflow and algorithm and rethink it for optimal speedup.  It's
  2814.     not uncommon to see one, two, or even three orders of magnitude of
  2815.     speed difference between the brute-force and the recoded approaches.
  2816.  
  2817.  
  2818. 2.33) What is variable suicide and how can I prevent it?
  2819.  
  2820.     Variable suicide is a nasty sideeffect of dynamic scoping and
  2821.     the way variables are passed by reference.  If you say
  2822.  
  2823.     $x = 17;
  2824.     &munge($x);
  2825.     sub munge {
  2826.         local($x);
  2827.         local($myvar) = $_[0];
  2828.         ...
  2829.     } 
  2830.  
  2831.     Then you have just clubbered $_[0]!  Why this is occurring 
  2832.     is pretty heavy wizardry: the reference to $x stored in 
  2833.     $_[0] was temporarily occluded by the previous local($x)
  2834.     statement (which, you're recall, occurs at run-time, not
  2835.     compile-time).  The work around is simple, however: declare
  2836.     your formal parameters first:
  2837.  
  2838.     sub munge {
  2839.         local($myvar) = $_[0];
  2840.         local($x);
  2841.         ...
  2842.     }
  2843.  
  2844.     That doesn't help you if you're going to be trying to access
  2845.     @_ directly after the local()s.  In this case, careful use
  2846.     of the package facility is your only recourse.
  2847.  
  2848.     Another manifestation of this problem occurs due to the
  2849.     magical nature of the index variable in a foreach() loop.
  2850.  
  2851.     @num = 0 .. 4;
  2852.     print "num begin  @num\n";
  2853.     foreach $m (@num) { &ug }
  2854.     print "num finish @num\n";
  2855.     sub ug {
  2856.         local($m) = 42;
  2857.         print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  2858.     }
  2859.     
  2860.     Which prints out the mysterious:
  2861.  
  2862.     num begin  0 1 2 3 4
  2863.     m=42  42,1,2,3
  2864.     m=42  0,42,2,3
  2865.     m=42  0,1,42,3
  2866.     m=42  0,1,2,42
  2867.     m=42  0,1,2,3
  2868.     num finish 0 1 2 3 4
  2869.  
  2870.     What's happening here is that $m is an alias for each 
  2871.     element of @num.  Inside &ug, you temporarily change
  2872.     $m.  Well, that means that you've also temporarily 
  2873.     changed whatever $m is an alias to!!  The only workaround
  2874.     is to be careful with global variables, using packages,
  2875.     and/or just be aware of this potential in foreach() loops.
  2876.  
  2877.     The perl5 static autos via "my" will not have this problem.
  2878.  
  2879.  
  2880. 2.34) Can I use Perl regular expressions to match balanced text?
  2881.  
  2882.     No, or at least, not by the themselves.
  2883.  
  2884.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  2885.     strictly regular because they do backtracking (the \1 notation), you
  2886.     still can't do it.  You need to employ auxiliary logic.  A simple
  2887.     approach would involve keeping a bit of state around, something 
  2888.     vaguely like this (although we don't handle patterns on the same line):
  2889.  
  2890.     while(<>) {
  2891.         if (/pat1/) {
  2892.         if ($inpat++ > 0) { warn "already saw pat1" } 
  2893.         redo;
  2894.         } 
  2895.         if (/pat2/) {
  2896.         if (--$inpat < 0) { warn "never saw pat1" } 
  2897.         redo;
  2898.         } 
  2899.     }
  2900.  
  2901.     A rather more elaborate subroutine to pull out balanced and possibly
  2902.     nested single chars, like ` and ', { and }, or ( and ) can be found
  2903.     on convex.com in /pub/perl/scripts/pull_quotes.
  2904.  
  2905.  
  2906. 2.35) Can I use Perl to run a telnet or ftp session?
  2907.  
  2908.     Sure, you can connect directly to them using sockets, or you can run a
  2909.     session on a pty.  In either case, Randal's chat2 package, which is
  2910.     distributed with the perl source, will come in handly.  It address
  2911.     much the same problem space as Don Libes's expect package does.  Two
  2912.     examples of using managing an ftp session using chat2 can be found on
  2913.     convex.com in /pub/perl/scripts/ftp-chat2.shar .
  2914.  
  2915.     Caveat lector: chat2 is documented only by example, may not run on
  2916.     System V systems, and is subtly machine dependent both in its ideas
  2917.     of networking and in pseudottys.
  2918.  
  2919.  
  2920. 2.36) What does "Malformed command links" mean?
  2921.  
  2922.     This is a bug in 4.035.  While in general it's merely a cosmetic
  2923.     problem, it often comanifests with a highly undesirable coredumping
  2924.     problem.  Programs known to be affected by the fatal coredump include
  2925.     plum and pcops.  Since perl5 is pretty much a total rewrite, we can
  2926.     count on it being fixed then, but if anyone tracks down the coredump
  2927.     problem before then, a significant portion of the Perl world would
  2928.     rejoice.
  2929.  
  2930.  
  2931. 2.37) How can I set up a footer format to be used with write()?
  2932.  
  2933.     While the $^ variable contains the name of the current header format,
  2934.     there is no corresponding mechanism to automatically do the same thing
  2935.     for a footer.  Not knowing how big a format is going to be until you
  2936.     evaluate it is one of the major problems.
  2937.  
  2938.     If you have a fixed-size footer, you can get footers by checking for
  2939.     line left on page ($-) before each write, and printing the footer
  2940.     yourself if necessary.
  2941.  
  2942.     Another strategy is to open a pipe to yourself, using open(KID, "|-")
  2943.     and always write()ing to the KID, who then postprocesses its STDIN to
  2944.     rearrange headers and footers however you like.  Not very convenient,
  2945.     but doable.
  2946.  
  2947.  
  2948. 2.38) Why does my Perl program keep growing in size?
  2949.  
  2950.     While there may be a real memory leak in the Perl source code or even
  2951.     whichever malloc() you're using, common causes are incomplete eval()s
  2952.     or local()s in loops.
  2953.  
  2954.     An eval() which terminates in error due to a failed parsing 
  2955.     will leave a bit of memory unusable.
  2956.  
  2957.     A local() inside a loop:
  2958.  
  2959.     for (1..100) {
  2960.         local(@array);
  2961.     } 
  2962.  
  2963.     will build up 100 versions of @array before the loop is done.
  2964.     The work-around is:
  2965.  
  2966.     local(@array);
  2967.     for (1..100) {
  2968.         undef @array;
  2969.     } 
  2970.  
  2971.     Larry reports that this behavior is fixed for perl5.
  2972.  
  2973.  
  2974. 2.39) Can I do RPC in Perl?
  2975.  
  2976.     Yes, you can, since Perl has access to sockets.  An example of the rup
  2977.     program written in Perl can be found in the script ruptime.pl at
  2978.     the scripts archive on coombs.anu.edu.au .   I warn you, however,
  2979.     that it's not a pretty site, as it's used nothing from h2ph or c2ph, 
  2980.     so everything is utterly hard-wired.
  2981.  
  2982.  
  2983. 2.40) What's the difference between delete and undef with %tables?
  2984.  
  2985.     Pictures help...  here's the %ary table:
  2986.  
  2987.           keys  values
  2988.         +------+------+
  2989.         |  a   |  3   |
  2990.         |  x   |  7   |
  2991.         |  d   |  0   |
  2992.         |  e   |  2   |
  2993.         +------+------+
  2994.  
  2995.     And these conditions hold
  2996.  
  2997.         $ary{'a'}                       is true
  2998.         $ary{'d'}                       is false
  2999.         defined $ary{'d'}               is true
  3000.         defined $ary{'a'}               is true
  3001.         grep ($_ eq 'a', keys %ary)     is true
  3002.  
  3003.     If you now say 
  3004.  
  3005.         undef $ary{'a'}
  3006.  
  3007.     your table now reads:
  3008.         
  3009.  
  3010.           keys  values
  3011.         +------+------+
  3012.         |  a   | undef|
  3013.         |  x   |  7   |
  3014.         |  d   |  0   |
  3015.         |  e   |  2   |
  3016.         +------+------+
  3017.  
  3018.     and these conditions now hold; changes in caps:
  3019.  
  3020.         $ary{'a'}                       is FALSE
  3021.         $ary{'d'}                       is false
  3022.         defined $ary{'d'}               is true
  3023.         defined $ary{'a'}               is FALSE
  3024.         grep ($_ eq 'a', keys %ary)     is true
  3025.  
  3026.     Notise the last two: you have an undef value, but a defined key!
  3027.  
  3028.     Now, consider this:
  3029.  
  3030.         delete $ary{'a'}
  3031.  
  3032.     your table now reads:
  3033.  
  3034.           keys  values
  3035.         +------+------+
  3036.         |  x   |  7   |
  3037.         |  d   |  0   |
  3038.         |  e   |  2   |
  3039.         +------+------+
  3040.  
  3041.     and these conditions now hold; changes in caps:
  3042.  
  3043.         $ary{'a'}                       is false
  3044.         $ary{'d'}                       is false
  3045.         defined $ary{'d'}               is true
  3046.         defined $ary{'a'}               is false
  3047.         grep ($_ eq 'a', keys %ary)     is FALSE
  3048.  
  3049.     See, the whole entry is gone!
  3050.  
  3051. 2.41) How do I do a "tail -f" in Perl?
  3052.  
  3053.     Larry says that the solution is to put a call to seek in yourself. 
  3054.     First try
  3055.  
  3056.         seek(GWFILE, 0, 1);
  3057.  
  3058.     If that doesn't work (depends on your stdio implementation), then
  3059.     you need something more like this:
  3060.  
  3061.  
  3062.     for(;;) {
  3063.         for ($curpos = tell(GWFILE); $_ = <GWFILE>; $curpos = tell(GWFILE)) {
  3064.            search for some stuff and put it into files
  3065.         }
  3066.         sleep for a while 
  3067.         seek(GWFILE, $curpos, 0);
  3068.     }
  3069. -- 
  3070.     Tom Christiansen      tchrist@cs.colorado.edu       
  3071.             Consultant
  3072.     Boulder Colorado  303-444-3212
  3073.